<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD My_ML ======= My_ML >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

My_ML

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD
<<<<<<< HEAD

13.MLg_title


.---. (13.MLg_title)

=======

13.MLg_title


.---. (13.MLg_title)

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

----------------------------------------------------------------------------------------
1) 'Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning'
----------------------------------------------------------------------------------------
def Week1 C1 "A new Programming Paradigm":
  - C1_W1_Lab_1_hello_world_nn (numbers) ".Dense(units=1, input_shape=[1])"
  - C1W1_Assignment_0 (numbers) "optimizer='sgd', loss='mean_squared_error'"
def Week2 C1 "Introduction to Computer Vision":
  - C1_W2_Lab_1_beyond_hello_world (fashion_mnist) ".Flatten(), activation=tf.nn.relu, 
  activation=tf.nn.softmax, optimizer = tf.optimizers.Adam()" 
  - C1_W2_Lab_2_callbacks (fashion_mnist) "loss = 'sparse_categorical_crossentropy' "
  - C1W2_Assignment_Callbacks_handwriting0_9 "metrics=['accuracy'] "
def Week3 C1 "Enhancing Vision with Convolutional Neural Networks":
  - C1_W3_Lab_1_improving_accuracy_using_convolutions (fashion_mnist) 
  "optimizer='adam', model.evaluate(test_images, test_labels) "
  - C1_W3_Lab_2_exploring_convolutions_Max Pooling(scipy, photo)
  "convolution (filter, weight), Max Pooling (max(pixels))"
  - C1W3_Assignment (mnist.npz)_Convolutions 
  "activation='relu', .Conv2D(), .MaxPooling2D() "
def Week4 C1 "Using Real-world Images":
  - C1_W4_Lab_1_image_generator_no_validation ('horse-or-human.zip') 
  "activation='sigmoid', loss='binary_crossentropy', optimizer=RMSprop(learning_rate=0.001)"
  - C1_W4_Lab_2_image_generator_with_validation (horse-or-human+validation)
  "ImageDataGenerator, train, valid, class_mode='binary', validation_datagen  "
  - C1_W4_Lab_3_compacted_images (horse-or-human+validation)
  "target_size = (150, 150) "
  - C1W4_Assignment (data_happy_sad.zip)
<<<<<<< HEAD


======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

======= -->

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

----------------------------------------------------------------------------------------
2) 'Convolutional Neural Networks in TensorFlow'
----------------------------------------------------------------------------------------
def Week1 C2 "Exploring a Larger Dataset":
  - C2_W1_Lab_1_cats_vs_dogs_Kaggle_small_set
   ".Conv2D(), .MaxPooling2D() "
  - C2W1_Assignment_cats-and-dogs_big_set
def Week2 C2 "Augmentation- A technique to avoid overfitting":
  - C2_W2_Lab_1_cats_v_dogs_filtered_augmentation
  - C2_W2_Lab_2_horses_v_humans_validation_augmentation
  - C2W2_Assignment_augmentation_CatsDogsFULL_(cats-and-dogs.zip)
def Week3 C2 "Transfer Learning":
  - C2_W3_Lab_1_transfer_learning_drop_(cats_and_dogs_filtered)
  "InceptionV3(include_top = False), model.load_weights(), layer.trainable = False "
  - C2W3_Assignment_augmentation_transver_drop(horse-or-human.zip)
  "x = layers.Flatten()(last_output),  x = layers.Dropout(0.2)(x) "
def Week4 C2 "Multiclass Classifications":
  - C2_W4_Lab_1_multi_class_classifier(rock, paper, scissors)rps.zip
  "loss = 'categorical_crossentropy', activation='softmax', class_mode='categorical'  "
  - C2W4_Assignment_Multi-class_Classification(english alphabet)
  "csv.reader(), np.expand_dims(training_images, -1), zip(*data), np.array(labels, dtype=np.float64), train_datagen.flow() "
<<<<<<< HEAD


======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

======= -->

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

----------------------------------------------------------------------------------------
3) 'Natural Language Processing in TensorFlow'
----------------------------------------------------------------------------------------
def Week1 C3 "Sentiment in text":
  - C3_W1_Lab_1_tokenize_basic  |  ".fit_on_texts(sentences), .word_index"
  - C3_W1_Lab_2_sequences_basic  |   "oov_token='<OOV>', .texts_to_sequences(sentences), 
  pad_sequences(sequences, maxlen=5), truncating='post',  padding='post',  truncating='pre' " 
  - C3_W1_Lab_3_sarcasm_Kaggle  |  "with open('./sarcasm.json', 'r') as f:, datastore = json.load(f)"
  - C3W1_Assignment_(BBC News)  |   "csv.reader(csvfile, delimiter=','), remove_stopwords('I am about'), tokenize_labels()"
def  Week2 C3 "Word Embeddings":
  - C3_W2_Lab_1_imdb  |   ".Embedding(vocab_size, embedding_dim, input_length=max_length), embedding_layer.get_weights()[0], files.download('vecs.tsv'), files.download('meta.tsv')"
  - C3_W2_Lab_2_sarcasm_classifier  |  "json.load(f), .GlobalAveragePooling1D(), files.download('vecs.tsv'), files.download('meta.tsv')"
  - C3_W2_Lab_3_imdb_subwords  |  "tokenizer_plaintext, tokenizer_subwords, 6307 ----> Ten, 2327 ----> sor,train_data, test_data = imdb_subwords['train'], db_subwords['test']"
  - C3W2_Assignment (Diving deeper into the BBC News archive)  |   "def_remove_stopwords(), def_parse_data_from_file(csv.reader()), .set_seed(123), .GlobalAveragePooling1D()"
def Week3 C3 "Assessments Overdue":
  - C3_W3_Lab_1_single_layer_LSTM(subword)  |  ".Embedding(), .Bidirectional(LSTM(32)), "
  - C3_W3_Lab_2_multiple_layer_LSTM(subword)  | ".Bidirectional(LSTM(32), return_sequences=True), .Bidirectional(LSTM(32))"
  - C3_W3_Lab_3_Conv1D  |  ".Embedding(), .Conv1D(filters, kernel_size, activation='relu'), .GlobalMaxPooling1D() "
  - C3_W3_Lab_4_imdb_reviews_with_GRU_LSTM_Conv1D  |  ".Flatten(), .Bidirectional(.LSTM(32)), .Bidirectional(.GRU(32)), .Conv1D(filters, kernel_size, activation='relu'), .GlobalMaxPooling1D()"
  - C3_W3_Lab_5_sarcasm_with_bi_LSTM  |  ".Bidirectional(tf.keras.layers.LSTM(lstm_dim))"
  - C3_W3_Lab_6_sarcasm_with_1D_conv  |  ".Conv1D(128, 5, activation='relu'), .GlobalMaxPooling1D()"
  - C3W3_Assignment_Exploring Overfitting in NLP(Sentiment140 dataset)  |  "only 10% dataset, linregress(), weights=[embeddings_matrix],  Best practice"
def Week4 C3 "Sequence models and literature":
  - C3_W4_Lab_1_Generating Text_NN  |  "Dense(total_words), .to_categorical(labels), model.add(Bidirectional(LSTM(20))),  seed_text='Laurence went to Dublin'"
  - C3_W4_Lab_2_irish_lyrics_1,692_sentences  |  "new_word=tokenizer.index_word[predicted], predicted=np.argsort(probabilities)[0][-choice]"
  - C3_W4_Lab_3_to generating Shakespeare Tensorflow RNN  |  "that uses character-based prediction, class MyModel(), class OneStep(), ids_from_chars, chars_from_ids, BIG INFORMATION"
  - C3W4_Assignment_Shakespeare classic RNN  |  ".add(Embedding(), .add(Bidirectional(LSTM(128)))"

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

----------------------------------------------------------------------------------------
4) 'Sequences, Time Series and Prediction '
----------------------------------------------------------------------------------------
def Week1 C4 "Sequences and Prediction":   |  ""
  - C4_W1_Lab_1_time_series  |  "trend, seasonality_pattern, seasonality, noise, autocorrelation, impulses, autocorrelation_impulses, Non-stationary Time Series"
  - C4_W1_Lab_2_forecasting   |  "Naive Forecast mse=61,8, mae=5,9, Moving Average mse=106.6, mae=7.1, Differencing mse=53.7, mae=5.9, Smoothing mse=34.3, mae=4.6"
  - C4W1_Assignment_time_series   |  "mse:19.58, mae:2.60 for naive, mse:65.79, mae:4.30 for moving average, mse:8.50, mae:2.33 for moving average plus past, mse:12.53, mae:2.20 for moving average plus smooth past"
def Week2 C4 "Deep Neural Networks for Time Series":
  - C4_W2_Lab_1_Preparing_Time_Series_features_and_labels  |  "tf.data.Dataset.range(10); dataset.window(size=5, shift=1, drop_remainder=True), .flat_map(lambda window: window.batch(5)), .map(lambda window: (window[:-1], window[-1])), .shuffle(buffer_size=10), .batch(2).prefetch(1) "
  - C4_W2_Lab_2_single_layer_NN(Time series)  |  "dataset.batch(batch_size).prefetch(1); tf.keras.layers.Dense(1, input_shape=[window_size]); tf.keras.models.Sequential([l0]); model.fit(dataset, epochs=100);  mse,mae:46,7; 5,1"
  - C4_W2_Lab_3_deep_NN(Time series)  |  "tf.keras.layers.Dense(10, ...); tf.keras.layers.Dense(10, ...); tf.keras.layers.Dense(1),  mse,mae:45,7;5,01; tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9); mse,mae:42,2; 4,8"
  - C4W2_Assignment_DNN(Time series):   |  "plot_series(), generate_time_series(), @dataclass, train_val_split(), windowed_dataset(), create_model(), compute_metrics(), generate_forecast(), mse:29.33, mae:3.33"
def Week3 C4 "Recurrent Neural Networks for Time Series":
  - C4_W3_Lab_1_RNN_for_time_series   |  "tf.keras.layers.Lambda(), .SimpleRNN(), .SimpleRNN(), .Dense(1), .Lambda(), learning_rate, mse:65.11, mae:6.25"
  - C4_W3_Lab_2_LSTM_for_time_series   |  ".clear_session(), .Lambda(), .Bidirectional(tf.keras.layers.LSTM(), .Bidirectional(.LSTM(), .Dense(1), .Lambda(), .compile(loss=tf.keras.losses.Huber(), learning_rate, mse:58.02, mae:5.48"
  - C4W3_Assignment RNNs(time series)   |  ".Lambda(), .Bidirectional(), .LSTM(32), create_uncompiled_model(), adjust_learning_rate(), create_model(), compute_metrics(), model_forecast()_ achieve an MAE of 4.5 or less, mse:28.74, mae:3.21, ! tar-czvf saved_model.tar.gz saved_model/"
def Week1 C4 "Real-world time series data":
  - C4_W4_Lab_1_Convolutions_with_LSTM   |  "init_weights = model.get_weights(), tf.keras.backend.clear_session(), model.set_weights(init_weights), .Conv1D(), .LSTM(64), .LSTM(64), .Lambda(); mse:46.32,mae:5.23(58,02; 5,8) "
  - C4_W4_Lab_2_Sunspots_DNN_Kaggle   |  ".LearningRateScheduler(), .clear_session(), .Dense(30), .Dense(10), .Dense(1); model_forecast(): for predict; mae:14,93"
  - C4_W4_Lab_3_Sunspots_CNN_RNN_DNN   |  "windowed_dataset(): for tuples features, labels; .Conv1D(), .LSTM(64), .LSTM(64), .Dense(30), .Dense(10), .Dense(1), .Lambda(), epochs=500,mae:14.43; epochs=100,mae:14.02; epochs=40,.ExponentialDecay(),mae:14,26, other lr_schedule; epochs=10,mae:14.92;"
  - C4W4_Assignment_min_temp_Melbourne   |  ".Conv1D(), .LSTM(64), .LSTM(64), .Dense(30), .Dense(10), .Dense(5), .Dense(1):  MSE<=6,MAE<=2: 5,41, 1,82"
<<<<<<< HEAD


======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

1) Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning (13.MLg_title)

(Введение в TensorFlow для искусственного интеллекта, машинного обучения и глубокого обучения)
Week1(c1): "A new Programming Paradigm"
Artificial intelligence: refers to technologies that enable computers and machines to perform advanced, human-like processes such as analyzing, learning, problem-solving, and decision-making.
Machine Learning: is a field of artificial intelligence that focuses on developing algorithms and models that enable computers to learn and make predictions or decisions without being explicitly programmed. It involves the study of statistical models and algorithms that can automatically analyze and interpret complex patterns and relationships in data.
Deep learning: is a subfield of artificial intelligence that focuses on training algorithms to learn and make decisions similar to humans. It is inspired by the structure and function of the human brain and uses artificial neural networks to process and analyze large amounts of data. Deep learning algorithms learn from examples and patterns to improve their performance over time.

======= -->

1) Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning (13.MLg_title)

(Введение в TensorFlow для искусственного интеллекта, машинного обучения и глубокого обучения)
Week1(c1): "A new Programming Paradigm"
Artificial intelligence: refers to technologies that enable computers and machines to perform advanced, human-like processes such as analyzing, learning, problem-solving, and decision-making.
Machine Learning: is a field of artificial intelligence that focuses on developing algorithms and models that enable computers to learn and make predictions or decisions without being explicitly programmed. It involves the study of statistical models and algorithms that can automatically analyze and interpret complex patterns and relationships in data.
Deep learning: is a subfield of artificial intelligence that focuses on training algorithms to learn and make decisions similar to humans. It is inspired by the structure and function of the human brain and uses artificial neural networks to process and analyze large amounts of data. Deep learning algorithms learn from examples and patterns to improve their performance over time.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W1L1_MachineLearning_DeepLearning.ipynb
---------------------------------------------------------------
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(xs, ys, epochs=500)
prediction = model.predict([10.0])

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W1LwAssignment_ML_DL_HousingPrices.ipynb
---------------------------------------------------------------
model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])]) 
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(xs, ys, epochs=1000)
prediction = model.predict([new_x])[0]

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Stochastic Gradient Descent - SGD:
Stochastic Gradient Descent (SGD) is an optimization algorithm commonly used in training machine learning models, particularly in the context of neural networks. It is a variant of the Gradient Descent algorithm and is designed to handle large datasets more efficiently.
Суть работы оптимизатора 'sgd' заключается в обновлении параметров (весов и смещений) в соответствии с градиентом функции потерь по отношению к этим параметрам. Различные вещные значения, известные как веса, связывают нейроны в сети.
Процесс обновления параметров происходит с использованием градиентного спуска: сначала вычисляется градиент функции потерь по каждому параметру, а затем каждый параметр обновляется путем вычитания определенного коэффициента, называемого шагом обучения, умноженного на соответствующий градиент.
В целом, оптимизатор 'sgd' позволяет эффективно настраивать параметры нейронной сети, минимизируя функцию потерь в процессе обучения.
Mean_squared_error:
Mean squared error (MSE) is a widely used metric for evaluating the performance of a regression model. It measures the average of the squares of the errors or the differences between actual and predicted values in the model's predictions.
The formula for calculating the mean squared error is:
MSE = (1/n) * Σ(actual - predicted)^2
Where:
n is the number of data points
Σ denotes the sum over all data points
actual represents the actual values of the target variable
predicted represents the predicted values from the regression model
Функция потерь 'mean_squared_error' (среднеквадратичная ошибка) вычисляется как средний квадрат разности между истинными значениями и прогнозируемыми значениями модели.

Week 1 Quiz(c1):
1) What is the difference between traditional programming and Machine Learning?:
2.(+) In traditional programming, a programmer has to formulate or cade rules manually, whereas, in Machine Learning, the algorithm automatically formulates the rules from the data.
2) What do we call the process of telling the computer what the data represents (i.e. this data is for walking, this data is for running)?:
4. (+)Labelling the Data
3) What is Dense layer?:
3.(+) A layer of connected neurons.
4)How do you measure how good the current 'guess' is?:
1.(+) Using the Loss function.
5) What does the optimizer do?:
2.(+) Generates a new and improved guess.
6) What is Convergence?:
3.(+) The process of getting very close to the correct answer.
7) What does model.fit do?:
3.(+) It trains the neural network to fit one set of values to another.

Week2(c1): "Introduction to Computer Vision"

=======

Stochastic Gradient Descent - SGD:
Stochastic Gradient Descent (SGD) is an optimization algorithm commonly used in training machine learning models, particularly in the context of neural networks. It is a variant of the Gradient Descent algorithm and is designed to handle large datasets more efficiently.
Суть работы оптимизатора 'sgd' заключается в обновлении параметров (весов и смещений) в соответствии с градиентом функции потерь по отношению к этим параметрам. Различные вещные значения, известные как веса, связывают нейроны в сети.
Процесс обновления параметров происходит с использованием градиентного спуска: сначала вычисляется градиент функции потерь по каждому параметру, а затем каждый параметр обновляется путем вычитания определенного коэффициента, называемого шагом обучения, умноженного на соответствующий градиент.
В целом, оптимизатор 'sgd' позволяет эффективно настраивать параметры нейронной сети, минимизируя функцию потерь в процессе обучения.
Mean_squared_error:
Mean squared error (MSE) is a widely used metric for evaluating the performance of a regression model. It measures the average of the squares of the errors or the differences between actual and predicted values in the model's predictions.
The formula for calculating the mean squared error is:
MSE = (1/n) * Σ(actual - predicted)^2
Where:
n is the number of data points
Σ denotes the sum over all data points
actual represents the actual values of the target variable
predicted represents the predicted values from the regression model
Функция потерь 'mean_squared_error' (среднеквадратичная ошибка) вычисляется как средний квадрат разности между истинными значениями и прогнозируемыми значениями модели.

Week 1 Quiz(c1):
1) What is the difference between traditional programming and Machine Learning?:
2.(+) In traditional programming, a programmer has to formulate or cade rules manually, whereas, in Machine Learning, the algorithm automatically formulates the rules from the data.
2) What do we call the process of telling the computer what the data represents (i.e. this data is for walking, this data is for running)?:
4. (+)Labelling the Data
3) What is Dense layer?:
3.(+) A layer of connected neurons.
4)How do you measure how good the current 'guess' is?:
1.(+) Using the Loss function.
5) What does the optimizer do?:
2.(+) Generates a new and improved guess.
6) What is Convergence?:
3.(+) The process of getting very close to the correct answer.
7) What does model.fit do?:
3.(+) It trains the neural network to fit one set of values to another.

Week2(c1): "Introduction to Computer Vision"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W2L1_ComputerVisionMNIST_clothing_images.ipynb
---------------------------------------------------------------
training_images = training_images / 255.0
test_images = test_images / 255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
                                    tf.keras.layers.Dense(128, activation=tf.nn.relu),
                                    tf.keras.layers.Dense(10, activation=tf.nn.softmax)])
model.compile(optimizer = tf.optimizers.Adam(),
              loss = 'sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
model.evaluate(test_images, test_labels)
classifications = model.predict(test_images)
<<<<<<< HEAD


======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

Flatten(): is a function in machine learning that transforms a multi-dimensional array or tensor into a one-dimensional array.
Dense(128): is a fully connected layer in a neural network with 128 neurons, which applies the rectified linear unit (ReLU) activation function.
Dense(10): is a fully connected layer in a neural network with 10 neurons, which applies the softmax activation function for multi-class classification problems.
Rectified linear unit (ReLU): is an activation function commonly used in deep learning that introduces non-linearity by outputting the input directly if it is positive or zero, and outputs zero otherwise.
The softmax: activation function is commonly used in multi-class classification tasks to convert the outputs of a neural network into a probability distribution over multiple classes, where the sum of all probabilities is equal to 1.
The optimizer 'adam': is an algorithm commonly used in deep learning that adapts the learning rate during training to improve the efficiency and convergence of the neural network model.
The 'adam' optimizer: combines the Adaptive Gradient Algorithm (AdaGrad) and Root Mean Square Propagation (RMSProp) algorithms to optimize the learning process. It adapts the learning rate for each parameter in the neural network based on the historical gradients, and also maintains per-parameter learning rates to adjust the updates accordingly.
The loss function 'sparse_categorical_crossentropy': is commonly used in multi-class classification tasks where the target variable is represented as an integer instead of one-hot encoding.
The metric 'accuracy': is commonly used in classification tasks to evaluate the performance of a model by measuring the proportion of correctly predicted labels compared to the total number of samples.
Input layer: in the shape of our data.
Output layer: in the shape of the number of categories we're trying to define.
Hidden layer: in the middle

======= -->

Flatten(): is a function in machine learning that transforms a multi-dimensional array or tensor into a one-dimensional array.
Dense(128): is a fully connected layer in a neural network with 128 neurons, which applies the rectified linear unit (ReLU) activation function.
Dense(10): is a fully connected layer in a neural network with 10 neurons, which applies the softmax activation function for multi-class classification problems.
Rectified linear unit (ReLU): is an activation function commonly used in deep learning that introduces non-linearity by outputting the input directly if it is positive or zero, and outputs zero otherwise.
The softmax: activation function is commonly used in multi-class classification tasks to convert the outputs of a neural network into a probability distribution over multiple classes, where the sum of all probabilities is equal to 1.
The optimizer 'adam': is an algorithm commonly used in deep learning that adapts the learning rate during training to improve the efficiency and convergence of the neural network model.
The 'adam' optimizer: combines the Adaptive Gradient Algorithm (AdaGrad) and Root Mean Square Propagation (RMSProp) algorithms to optimize the learning process. It adapts the learning rate for each parameter in the neural network based on the historical gradients, and also maintains per-parameter learning rates to adjust the updates accordingly.
The loss function 'sparse_categorical_crossentropy': is commonly used in multi-class classification tasks where the target variable is represented as an integer instead of one-hot encoding.
The metric 'accuracy': is commonly used in classification tasks to evaluate the performance of a model by measuring the proportion of correctly predicted labels compared to the total number of samples.
Input layer: in the shape of our data.
Output layer: in the shape of the number of categories we're trying to define.
Hidden layer: in the middle

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= callbacks = myCallback() model.fit(x_train, y_train, epochs=10, callbacks=[callbacks]) --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W2L2_MNIST_Callbacks.ipynb
---------------------------------------------------------------
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(512, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if(logs.get('loss') < 0.4):
      print("\nLoss is lower than 0.4 so cancelling training!")
      self.model.stop_training = True
<<<<<<< HEAD

callbacks = myCallback()
model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])


======= callbacks = myCallback() model.fit(x_train, y_train, epochs=10, callbacks=[callbacks]) >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

======= callbacks = myCallback() model.fit(x_train, y_train, epochs=10, callbacks=[callbacks]) -->

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W2LwAssignment_datasetMNIST_handwriting0_9.ipynb
---------------------------------------------------------------
x_train = x_train / 255.0
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epochs, logs={}):
    if logs.get("accuracy") is not None and logs.get("accuracy") > 0.99:
      print("\nReached 99% accuracy so cancelling training!")
      self.model.stop_training = True
<<<<<<< HEAD

callbacks = myCallback() 
 
=======
callbacks = myCallback() 
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def train_mnist(x_train, y_train):
  model = tf.keras.models.Sequential([
      tf.keras.layers.Flatten(input_shape=(28, 28)),
      tf.keras.layers.Dense(128, activation=tf.nn.relu),
      tf.keras.layers.Dense(10, activation=tf.nn.softmax)  ])
  model.compile(optimizer='adam',
                loss='sparse_categorical_crossentropy',
                metrics=['accuracy'])
  history = model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])
<<<<<<< HEAD

  return history

hist = train_mnist(x_train, y_train)

======= return history hist = train_mnist(x_train, y_train) >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 2 Quiz(c1):
1) What is the resolution of o the 70,000 images from the Fashion MNIST dataset?:
2. 28x28 Grayscale (+)
2) Why are there 10 output neurons in the Neural Network used as an example for the Computer Vision Problem?:
1. There are 10 different labels (+)
3) What does Relu do?:
4. It only returns x if x is greater then zero(+)
4) Why do you split data into training and test sets?:
3. To test a network with previously unseen data(+)
5)True or False: The on_epoch_end function sends a logs object with lots of great information about the current state of training at the start of every epoch:
1 False
6) Why do you set the callbacks=parameter in your fit function?:
3. So. on every epoch you can call back to a code function(+)

Week3(c1): "Enhancing Vision with Convolutional Neural Networks"

=======

Week 2 Quiz(c1):
1) What is the resolution of o the 70,000 images from the Fashion MNIST dataset?:
2. 28x28 Grayscale (+)
2) Why are there 10 output neurons in the Neural Network used as an example for the Computer Vision Problem?:
1. There are 10 different labels (+)
3) What does Relu do?:
4. It only returns x if x is greater then zero(+)
4) Why do you split data into training and test sets?:
3. To test a network with previously unseen data(+)
5)True or False: The on_epoch_end function sends a logs object with lots of great information about the current state of training at the start of every epoch:
1 False
6) Why do you set the callbacks=parameter in your fit function?:
3. So. on every epoch you can call back to a code function(+)

Week3(c1): "Enhancing Vision with Convolutional Neural Networks"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W3L1_MNISTfashin_DL_Convolutions.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax) ])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
print(f'\nMODEL EVALUATION')
test_loss = model.evaluate(test_images, test_labels)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if (logs.get('loss') < 0.3):
      print("\nLoss is lower than 0.3 so cancelling training!")
      self.model.stop_training = True
<<<<<<< HEAD

callbacks = myCallback()

=======
callbacks = myCallback()
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax) ])
model.summary()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5, callbacks=[callbacks])
print(f'\nMODEL EVALUATION')
test_loss = model.evaluate(test_images, test_labels)

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Convolutional Neural Networks (CNNs): are a type of deep learning algorithm designed for processing and analyzing visual data such as images. They consist of multiple layers of convolutional filters that extract hierarchical features from the input data, followed by pooling layers to decrease spatial dimensions, and fully connected layers for classification or regression tasks.
DNN stands for Deep Neural Network: in machine learning. It is a type of artificial neural network that is composed of multiple layers of interconnected nodes, or neurons.
Convolutions: involve applying a filter to an input to produce a feature map, which helps capture spatial relationships and patterns in the data.
Pooling:, on the other hand, involves downsampling the feature maps by aggregating nearby values, reducing the spatial dimensions of the data while retaining important information.
.Conv2D: is a layer in a convolutional neural network (CNN) that performs 2D convolution on input data. It aims to extract spatial features from the input using a specified number of filters
.MaxPooling2D: is a layer in a convolutional neural network (CNN) that performs downsampling by selecting the maximum value in a specific region of the input feature map. It helps to reduce the spatial dimensions of the feature map, while retaining the most important features, and aids in extracting invariant and robust features for image analysis tasks.

=======

Convolutional Neural Networks (CNNs): are a type of deep learning algorithm designed for processing and analyzing visual data such as images. They consist of multiple layers of convolutional filters that extract hierarchical features from the input data, followed by pooling layers to decrease spatial dimensions, and fully connected layers for classification or regression tasks.
DNN stands for Deep Neural Network: in machine learning. It is a type of artificial neural network that is composed of multiple layers of interconnected nodes, or neurons.
Convolutions: involve applying a filter to an input to produce a feature map, which helps capture spatial relationships and patterns in the data.
Pooling:, on the other hand, involves downsampling the feature maps by aggregating nearby values, reducing the spatial dimensions of the data while retaining important information.
.Conv2D: is a layer in a convolutional neural network (CNN) that performs 2D convolution on input data. It aims to extract spatial features from the input using a specified number of filters
.MaxPooling2D: is a layer in a convolutional neural network (CNN) that performs downsampling by selecting the maximum value in a specific region of the input feature map. It helps to reduce the spatial dimensions of the feature map, while retaining the most important features, and aids in extracting invariant and robust features for image analysis tasks.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W3L2_convolutions_filters_and_pools.ipynb
---------------------------------------------------------------
filter = [ [-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] 
weight  = 1
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
for x in range(1, size_x-1):
  for y in range(1, size_y-1):
    convolution = 0.0
    convolution = convolution + (ascent_image[x-1, y-1] * filter[0][0])
    convolution = convolution + (ascent_image[x-1, y] * filter[0][1])
    convolution = convolution + (ascent_image[x-1, y+1] * filter[0][2])
    convolution = convolution + (ascent_image[x, y-1] * filter[1][0])
    convolution = convolution + (ascent_image[x, y] * filter[1][1])
    convolution = convolution + (ascent_image[x, y+1] * filter[1][2])
    convolution = convolution + (ascent_image[x+1, y-1] * filter[2][0])
    convolution = convolution + (ascent_image[x+1, y] * filter[2][1])
    convolution = convolution + (ascent_image[x+1, y+1] * filter[2][2])
<<<<<<< HEAD

    convolution = convolution * weight

=======
    convolution = convolution * weight
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
    if (convolution<0):
      convolution=0
    if (convolution>255):
      convolution=255
<<<<<<< HEAD

    # Load into the transformed image
    image_transformed[x, y] = convolution

# Effect of Max Pooling
new_x = int(size_x/2)
new_y = int(size_y/2)

# Create blank image with reduced dimensions
newImage = np.zeros((new_x, new_y))

=======
    # Load into the transformed image
    image_transformed[x, y] = convolution
# Effect of Max Pooling
new_x = int(size_x/2)
new_y = int(size_y/2)
# Create blank image with reduced dimensions
newImage = np.zeros((new_x, new_y))
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Iterate over the image
for x in range(0, size_x, 2):
  for y in range(0, size_y, 2):
    # Store all the pixel values in the (2,2) pool
    pixels = []
    pixels.append(image_transformed[x, y])
    pixels.append(image_transformed[x+1, y])
    pixels.append(image_transformed[x, y+1])
    pixels.append(image_transformed[x+1, y+1])
    # Get only the largest value and assign to the reduced image
    newImage[int(x/2), int(y/2)] = max(pixels)

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W3LwAssignment_Improve_MNIST_with_Convolutions.ipynb
---------------------------------------------------------------
def reshape_and_normalize(images):
  # Reshape the images to add an extra dimension
  images = images.reshape((60000, 28, 28, 1))
  # Normalize pixel values
  images = images / 255.0
  return images
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if (logs.get('accuracy') > 0.995):
      print("\Reached 99.5% accuracy so cancelling training!")
      self.model.stop_training = True
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Convolutional Model
def convolutional_model():
  model = tf.keras.models.Sequential([
          tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(28,28,1)),
          tf.keras.layers.MaxPooling2D(2,2),
          tf.keras.layers.Flatten(),
          tf.keras.layers.Dense(352, activation='relu'),
          tf.keras.layers.Dense(10, activation='softmax') ])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
  model.compile(optimizer='adam',
                loss='sparse_categorical_crossentropy',
                metrics=['accuracy'])
  return model
<<<<<<< HEAD

from tensorflow.python.ops.check_ops import assert_less

=======
from tensorflow.python.ops.check_ops import assert_less
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = convolutional_model()
model_params = model.count_params()
assert model_params < 1000000, (
    f'Your model has {model_params:, } params.  For successful grading, please keep it '
    f'under 1,000,000 by reducing the number of units in your Conv2D and/or Dense layers.')
<<<<<<< HEAD

callbacks = myCallback()

history = model.fit(training_images, training_labels, epochs=10, callbacks=[callbacks])

======= callbacks = myCallback() history = model.fit(training_images, training_labels, epochs=10, callbacks=[callbacks]) >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 3 Quiz(c1):
1) How do Convolutions improve image recognition?:
4. They isolate features in images (+)
2) What does the Pooling technique do to the images?:
4. Reduces information in them while maintaining some features (+)
3) True or False. If you pass a 28x28 image through a 3x3 filter the output will be 26x26?:
True (+)
4) After max pooling a 26x26 image with a 2x2 filter, the output will be 56x56?:
False (+)
5) How does using Convolutions in out Deep neural network impact training?:
2. Its impact will depend on other factors (+)

Week4(c1): "Using Real-world Images"

=======

Week 3 Quiz(c1):
1) How do Convolutions improve image recognition?:
4. They isolate features in images (+)
2) What does the Pooling technique do to the images?:
4. Reduces information in them while maintaining some features (+)
3) True or False. If you pass a 28x28 image through a 3x3 filter the output will be 26x26?:
True (+)
4) After max pooling a 26x26 image with a 2x2 filter, the output will be 56x56?:
False (+)
5) How does using Convolutions in out Deep neural network impact training?:
2. Its impact will depend on other factors (+)

Week4(c1): "Using Real-world Images"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W4L1_image_generator_no_validation.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid') ])
model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.optimizers import RMSprop
model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(learning_rate=0.001),
              metrics=['accuracy'])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Data Preprocessing
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1/255.0)
# Flow training images in batches of 128 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
    './horse-or-human/',
    target_size=(300, 300),
    batch_size=128,
    class_mode='binary' )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
history = model.fit(train_generator,
                    steps_per_epoch=8,
                    epochs=15,
                    verbose=2)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Model Prediction
if classes[0]>0.5:
    print(fn + '\nis a human')
  else:
    print(fn + '\nis a horse')
<<<<<<< HEAD

# Visualizing Intermediate Representations

======= # Visualizing Intermediate Representations >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

The loss function 'binary_crossentropy': is commonly used in binary classification tasks where the output variable is binary (0 or 1).
The optimizer 'RMSprop': is an algorithm commonly used in deep learning that adapts the learning rate during training by dividing the learning rate for a weight by the square root of the exponentially weighted average of the squares of past gradients.
Sigmoid:
The sigmoid function is a type of mathematical function that can be used to introduce non-linearity into the output of a neuron. Specifically, in the context of neural network activations, the sigmoid function is often used to squash the output of a neuron between 0 and 1, which can be interpreted as a probability.

=======

The loss function 'binary_crossentropy': is commonly used in binary classification tasks where the output variable is binary (0 or 1).
The optimizer 'RMSprop': is an algorithm commonly used in deep learning that adapts the learning rate during training by dividing the learning rate for a weight by the square root of the exponentially weighted average of the squares of past gradients.
Sigmoid:
The sigmoid function is a type of mathematical function that can be used to introduce non-linearity into the output of a neuron. Specifically, in the context of neural network activations, the sigmoid function is often used to squash the output of a neuron between 0 and 1, which can be interpreted as a probability.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W4L2_image_generator_with_validation.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid') ])
model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.optimizers import RMSprop
model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(learning_rate=0.001),
              metrics=['accuracy'])
<<<<<<< HEAD

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1/255.0)
validation_datagen = ImageDataGenerator(rescale = 1/255.0)

=======
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1/255.0)
validation_datagen = ImageDataGenerator(rescale = 1/255.0)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
train_generator = train_datagen.flow_from_directory(
    './horse-or-human/',
    target_size=(300, 300),
    batch_size=128,
    class_mode='binary')
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
validation_datagen generator
validation_generator = validation_datagen.flow_from_directory(
    './validation-horse-or-human/',
    target_size=(300, 300),
    batch_size=32,
    class_mode='binary' )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
history = model.fit(
    train_generator,
    steps_per_epoch=8,
    epochs=15,
    verbose=1,
    validation_data = validation_generator,
    validation_steps=8)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Model Prediction
if classes[0]>0.5:
    print(fn + "\n is a human")
  else:
    print(fn + "\n is a horse")
<<<<<<< HEAD

# Visualizing Intermediate Representations

======= # Visualizing Intermediate Representations >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W4L3_compacted_images.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape = (150, 150, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(2, 2),
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.optimizers import RMSprop
model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(learning_rate=0.001),
              metrics=['accuracy'])
<<<<<<< HEAD

from tensorflow.keras.preprocessing.image import ImageDataGenerator

# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1/255)
validation_datagen = ImageDataGenerator(rescale=1/255)

=======
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1/255)
validation_datagen = ImageDataGenerator(rescale=1/255)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Flow training images in batches of 128 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
    './horse-or-human/',
    target_size = (150, 150),
    batch_size = 128,
    class_mode = 'binary')
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Flow training images in batches of 128 using train_datagen generator
validation_generator = validation_datagen.flow_from_directory(
    './validation-horse-or-human/',
    target_size = (150, 150),
    batch_size = 32,
    class_mode = 'binary') 
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
history = model.fit(
    train_generator,
    steps_per_epoch = 8,
    epochs = 15,
    verbose = 1,
    validation_data = validation_generator,
    validation_steps = 8)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Model Prediction
if classes[0]>0.5:
    print(fn + "\n is a human")
  else:
    print(fn + "\n is a horse")

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C1W4LwAssignment_Happy_Sad_Dataset.ipynb
---------------------------------------------------------------
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if logs.get('accuracy') is not None and logs.get('accuracy') > 0.999:
      print("\nReached 99.9% accuracy so cancelling training!")
      self.model.stop_training = True
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def image_generator():
  train_datagen = ImageDataGenerator(rescale=1/255.0)
  train_generator = train_datagen.flow_from_directory(directory=base_dir,
                                                      target_size=(150, 150),
                                                      batch_size=10,
                                                      class_mode='binary')
  return train_generator
<<<<<<< HEAD

gen = image_generator()

=======
gen = image_generator()
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def train_happy_sad_model(train_generator):
  callbacks = myCallback()
  model = tf.keras.models.Sequential([
      tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(150, 150, 3)),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(512, activation='relu'),
      tf.keras.layers.Dense(1, activation='sigmoid') ])
  model.compile(loss=losses.BinaryCrossentropy(),
                optimizer = optimizers.RMSprop(),
                metrics = ['accuracy'])
  history = model.fit(x=gen,
                      epochs=20,
                      verbose=1,
                      callbacks=[callbacks])
  return history
<<<<<<< HEAD

hist = train_happy_sad_model(gen)

======= hist = train_happy_sad_model(gen) >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 4 Quiz(c1):
1) Using Image Generator, how do you label images?:
4. It's based on the directory the image is contained in(+)
2) What method on the Image Generator is used to normalize the image?:
1. rescale(+)
3 )How did we specify the training size for the images?:
2. The target_size parameter on the training generator(+)
4) When we specify the input_shape to be (300, 300, 3), what does that mean?:
4. Every image will be 300x300 pixels, with 3 bytes to define color (+)
5) If your training data is close to 1.000 accuracy, but your validation data isn't, what's the risk here?:
3. You're overfitting on your training data (+)
6) Convolution Neural Networks are better for classifying images like horses and humans because:
3. In these images, the features may be in different parts of the frame (+)
7) After reducing the size of the images, the training results were different. Why?:
4. We removed some convolutions to handle the smaller images (+)

2) Convolutional Neural Networks in TensorFlow (13.MLg_title)

Week1(c2): "Exploring a Larger Dataset"
(Изучение большего набора данных)
Convolutional Neural Networks (CNNs): are a type of deep learning algorithm designed for processing and analyzing visual data such as images. They consist of multiple layers of convolutional filters that extract hierarchical features from the input data, followed by pooling layers to decrease spatial dimensions, and fully connected layers for classification or regression tasks.

=======

Week 4 Quiz(c1):
1) Using Image Generator, how do you label images?:
4. It's based on the directory the image is contained in(+)
2) What method on the Image Generator is used to normalize the image?:
1. rescale(+)
3 )How did we specify the training size for the images?:
2. The target_size parameter on the training generator(+)
4) When we specify the input_shape to be (300, 300, 3), what does that mean?:
4. Every image will be 300x300 pixels, with 3 bytes to define color (+)
5) If your training data is close to 1.000 accuracy, but your validation data isn't, what's the risk here?:
3. You're overfitting on your training data (+)
6) Convolution Neural Networks are better for classifying images like horses and humans because:
3. In these images, the features may be in different parts of the frame (+)
7) After reducing the size of the images, the training results were different. Why?:
4. We removed some convolutions to handle the smaller images (+)

2) Convolutional Neural Networks in TensorFlow (13.MLg_title)

Week1(c2): "Exploring a Larger Dataset"
(Изучение большего набора данных)
Convolutional Neural Networks (CNNs): are a type of deep learning algorithm designed for processing and analyzing visual data such as images. They consist of multiple layers of convolutional filters that extract hierarchical features from the input data, followed by pooling layers to decrease spatial dimensions, and fully connected layers for classification or regression tasks.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W1L1_CNNs_CatsAndDog.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(150, 150, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid') ])
model.summary()
<<<<<<< HEAD

from tensorflow.keras.optimizers import RMSprop

model.compile(optimizer=RMSprop(learning_rate=0.001),
              loss='binary_crossentropy',
              metrics=['accuracy'])

=======
from tensorflow.keras.optimizers import RMSprop
model.compile(optimizer=RMSprop(learning_rate=0.001),
              loss='binary_crossentropy',
              metrics=['accuracy'])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1.0/255.0)
test_datagen = ImageDataGenerator(rescale=1.0/255.0)
train_generator = train_datagen.flow_from_directory(train_dir,
                                                    batch_size=20,
                                                    class_mode='binary',
                                                    target_size=(150, 150))
validation_generator = test_datagen.flow_from_directory(validation_dir,
                                                        batch_size=20,
                                                        class_mode='binary',
                                                        target_size = (150, 150))
history = model.fit(
    train_generator,
    epochs=15,
    validation_data=validation_generator,
    verbose=2 )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Model Prediction
  if classes[0]>0.5:
    print(fn + " is a dog")
  else:
    print(fn + " is a cat")
<<<<<<< HEAD

# Visualizing Intermediate Representations

=======
# Visualizing Intermediate Representations
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Plot training and validation accuracy per epoch
# Plot training and validation loss per epoch

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W1_Assignment_cats-and-dogs_big_set.ipynb
---------------------------------------------------------------
def train_val_generators(TRAINING_DIR, VALIDATION_DIR):
  train_datagen = ImageDataGenerator(rescale = 1.0 / 255.0)
  train_generator = train_datagen.flow_from_directory(
                                  directory   = TRAINING_DIR,
                                  batch_size  = 150,
                                  class_mode  = 'binary',
                                  target_size = (150, 150) )
  validation_datagen = ImageDataGenerator(rescale = 1.0 / 255.0)
  validation_generator = validation_datagen.flow_from_directory(
                                  directory = VALIDATION_DIR,
                                  batch_size  = 150,
                                  class_mode  = 'binary',
                                  target_size = (150, 150) )
  return train_generator, validation_generator
train_generator, validation_generator = train_val_generators(TRAINING_DIR, VALIDATION_DIR)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model():
  model = tf.keras.models.Sequential([
      tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(150, 150, 3)),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(512, activation='relu'),
      tf.keras.layers.Dense(1, activation='sigmoid')  ])
  from tensorflow.keras.optimizers import RMSprop
  model.compile(optimizer = RMSprop(learning_rate = 0.001),
                loss = 'binary_crossentropy',
                metrics = ['accuracy'])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = create_model()
history = model.fit(train_generator,
                    epochs = 15,
                    verbose = 2,
                    validation_data=validation_generator)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Plot training and validation accuracy per epoch
# Plot training and validation loss per epoch

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 1 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1) What does flow_from_directory give you on the ImageDataGenerator?:
1. The ability to easily load images for training
2. The ability to pick the size of training images
3. The ability to automatically label images based on their directory name
4. All of the above (+)
2) If my Image is sized 150x150, and I pass a 3x3 Convolution over it, what size is the resulting image?:
4. 148x148(+)
3) If my data is sized 150x150, and I use Pooling if size 2X2, what size will the resulting image be?:
4. 75x75 (+)
4) If I want to view the history of my training, how can I access it?:
1. Create a variable 'history and assign it to the return of model.fit or model.fit_generator (+)
5) What's the name of the API that allows you to inspect the impact of convolutions in the images?:
4. The model.layers API (+)
6) When exploring the graphs, the loss levelled out at about .75 after 2 epochs, but the accuracy climbed close to 1.0 after 15 epochs. What's the significance of this?:
2. There was no point training after 2 epochs, as we overfit to the taring data (+)
7) Why is the validation accuracy a better indicator of model performance than training accuracy?:
3. The validation accuracy is based on images that the model hasn't been trained with, and this a better indicator of how the model will perform with new images(+)
8)Why is overfitting more likely to occur on smaller datasets?:
4. Because there's less likelihood of all possible features being encountered in the training process(+)

Week2(c2): "Augmentation: A technique to avoid overfitting" (Convolutional Neural Networks in TensorFlow)
# Data augmentation
# train_datagen = ImageDataGenerator(
# rotation_range=40,
# width_shift_range=0.2,
# height_shift_range=0.2,
# shear_range=0.2,
# zoom_range=0.2,
# horizontal_flip=True,
# fill_mode='nearest')
# - rotation_range - is a value in degrees (0–180) within which to randomly rotate pictures.
# - width_shift - and height_shift are ranges (as a fraction of total width or height)
# within which to randomly translate pictures vertically or horizontally.
# - shear_range - is for randomly applying shearing transformations.
# - zoom_range - is for randomly zooming inside pictures.
# - horizontal_flip - is for randomly flipping half of the images horizontally.
# This is relevant when there are no assumptions of horizontal assymmetry
# (e.g. real-world pictures).
# - fill_mode - is the strategy used for filling in newly created pixels, which
# can appear after a rotation or a width/height shift.

=======

Week 1 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1) What does flow_from_directory give you on the ImageDataGenerator?:
1. The ability to easily load images for training
2. The ability to pick the size of training images
3. The ability to automatically label images based on their directory name
4. All of the above (+)
2) If my Image is sized 150x150, and I pass a 3x3 Convolution over it, what size is the resulting image?:
4. 148x148(+)
3) If my data is sized 150x150, and I use Pooling if size 2X2, what size will the resulting image be?:
4. 75x75 (+)
4) If I want to view the history of my training, how can I access it?:
1. Create a variable 'history and assign it to the return of model.fit or model.fit_generator (+)
5) What's the name of the API that allows you to inspect the impact of convolutions in the images?:
4. The model.layers API (+)
6) When exploring the graphs, the loss levelled out at about .75 after 2 epochs, but the accuracy climbed close to 1.0 after 15 epochs. What's the significance of this?:
2. There was no point training after 2 epochs, as we overfit to the taring data (+)
7) Why is the validation accuracy a better indicator of model performance than training accuracy?:
3. The validation accuracy is based on images that the model hasn't been trained with, and this a better indicator of how the model will perform with new images(+)
8)Why is overfitting more likely to occur on smaller datasets?:
4. Because there's less likelihood of all possible features being encountered in the training process(+)

Week2(c2): "Augmentation: A technique to avoid overfitting" (Convolutional Neural Networks in TensorFlow)
# Data augmentation
# train_datagen = ImageDataGenerator(
# rotation_range=40,
# width_shift_range=0.2,
# height_shift_range=0.2,
# shear_range=0.2,
# zoom_range=0.2,
# horizontal_flip=True,
# fill_mode='nearest')
# - rotation_range - is a value in degrees (0–180) within which to randomly rotate pictures.
# - width_shift - and height_shift are ranges (as a fraction of total width or height)
# within which to randomly translate pictures vertically or horizontally.
# - shear_range - is for randomly applying shearing transformations.
# - zoom_range - is for randomly zooming inside pictures.
# - horizontal_flip - is for randomly flipping half of the images horizontally.
# This is relevant when there are no assumptions of horizontal assymmetry
# (e.g. real-world pictures).
# - fill_mode - is the strategy used for filling in newly created pixels, which
# can appear after a rotation or a width/height shift.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W2L1_Augmentation_CatsDogs.ipynb
---------------------------------------------------------------
def create_model():
  model = tf.keras.models.Sequential([
      tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(512, activation='relu'),
      tf.keras.layers.Dense(1, activation='sigmoid')  ])
  model.compile(loss='binary_crossentropy',
                optimizer=RMSprop(learning_rate=1e-4),
                metrics=['accuracy'])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_datagen generator
train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size=(150, 150),
    batch_size=20,
    class_mode='binary' )
test_datagen generator
validation_generator = test_datagen.flow_from_directory(
    validation_dir,
    target_size=(150, 150),
    batch_size=20,
    class_mode='binary' )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
EPOCHS = 100
model = create_model()
history = model.fit(
    train_generator,
    steps_per_epoch=100, # 2000 images = batch_size * steps
    epochs=EPOCHS,
    validation_data=validation_generator,
    validation_steps=50, # 1000 images = batch_size * steps
    verbose=1 )
<<<<<<< HEAD

import matplotlib.pyplot as plt

=======
import matplotlib.pyplot as plt
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def plot_loss_acc(history):
  acc = history.history['accuracy']
  val_acc = history.history['val_accuracy']
  loss = history.history['loss']
  val_loss = history.history['val_loss']
  epochs = range(len(acc))
  plt.plot(epochs, acc, 'bo', label='Training_accuracy')
  plt.plot(epochs, val_acc, 'b', label='Validation_accuracy')
  plt.title('Training adn validation accuracy')
  plt.grid(True)
  plt.legend()
  plt.figure()
  plt.plot(epochs, loss, 'bo', label='Training Loss')
  plt.plot(epochs, val_loss, 'b', label='Validation Loss')
  plt.title('Training and validation los')
  plt.grid(True)
  plt.legend()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Create new model
model_for_aug = create_model()
# This code has changed. Now instead of the ImageGenerator just rescaling
# the image, we also rotate and do other operations
train_datagen = ImageDataGenerator(
    rescale = 1./255,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    fill_mode='nearest')
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size=(150, 150),
    batch_size=20,
    class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
    validation_dir,
    target_size=(150, 150),
    batch_size=20,
    class_mode='binary')
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
history_with_aug = model_for_aug.fit(
    train_generator,
    steps_per_epoch=100, # 2000 images = batch_size * steps
    epochs=EPOCHS,
    validation_data=validation_generator,
    validation_steps=50,  # 1000 images = batch_size * steps
    verbose=1)
<<<<<<< HEAD

plot_loss_acc(history_with_aug)

======= plot_loss_acc(history_with_aug) >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W2L2_Augmentation_horses_v_humans.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(300, 300, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
<<<<<<< HEAD

    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid') ])

=======
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid') ])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.optimizers import RMSprop
model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(learning_rate=1e-4),
              metrics=['accuracy'])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    fill_mode='nearest' )
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    'tmp/horse-or-human/',
    target_size=(300, 300),
    batch_size=128,
    class_mode='binary'  )
validation_generator = validation_datagen.flow_from_directory(
    'tmp/validation-horse-or-human/',
    target_size=(300, 300),
    batch_size=32,
    class_mode='binary'  )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
EPOCHS = 100
history = model.fit(
    train_generator,
    steps_per_epoch=8,
    epochs=EPOCHS,
    verbose=1,
    validation_data = validation_generator,
    validation_steps=8)

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W2LwAssignment_TackleOverfitting_Augmentation_CatsDogsFULL.ipynb
---------------------------------------------------------------
def train_val_generators(TRAININT_DIR, VALIDATION_DIR):
  train_datagen = ImageDataGenerator(rescale=1./255.,
                                     rotation_range=40,
                                     width_shift_range=0.2,
                                     height_shift_range=0.2,
                                     shear_range=0.2,
                                     zoom_range=0.2,
                                     horizontal_flip=True,
                                     fill_mode='nearest')
  train_generator = train_datagen.flow_from_directory(directory=TRAININT_DIR,
                                                    batch_size=29,
                                                    class_mode='binary',
                                                    target_size=(150, 150))
  validation_datagen = ImageDataGenerator(rescale=1./255.)
  validation_generator = validation_datagen.flow_from_directory(directory=VALIDATION_DIR,
                                                                batch_size=20,
                                                                class_mode='binary',
                                                                target_size=(150, 150))
  return train_generator, validation_generator
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model():
  model = tf.keras.models.Sequential([
      tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)),
      tf.keras.layers.MaxPooling2D(2,2),
      tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2,2),
      tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2,2),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(128, activation='relu'),
      tf.keras.layers.Dense(1, activation='sigmoid')  ])
  from tensorflow.keras.optimizers import RMSprop
  model.compile(optimizer=RMSprop(learning_rate=0.001),
                loss='binary_crossentropy',
                metrics=['accuracy'])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = create_model()
history = model.fit(train_generator,
                    epochs=50,
                    verbose=1,
                    validation_data=validation_generator)

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 2 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1) How do you use Image Augmentation in TensorFlow:
2. Using parameters to the ImageDataGenerator (+)
2) If me training data only has people facing left, but I want to classify people facing right, how would I avoid overfitting?:
2. Use the 'horizontal_flip' parameter(+)
3) After adding data augmentation and using the same batch size and steps per epoch, you noticed that each training epoch became a little slower than when you trained without it. Why?:
1. Because the image preprocessing takes cycles (+)
4) What does the fill_mode parameter do?:
3. It attempts to recreate lost information after a transformation like a shear(+)
5) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk:
3. Nothing, all augmentation is done in-memory(+)
6) How does Image Augmentation help solve overfitting?:
2. It manipulates the training set to generate more scenarios for features in the images (+)
7) When using Image Augmentation my training gets:
1. Slower (+)
8) Using Image Augmentation effectively simulates having a larger data set for training:
1. False
2. True (+)

Week3(c2): "Transfer Learning" (Convolutional Neural Networks in TensorFlow)

=======

Week 2 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1) How do you use Image Augmentation in TensorFlow:
2. Using parameters to the ImageDataGenerator (+)
2) If me training data only has people facing left, but I want to classify people facing right, how would I avoid overfitting?:
2. Use the 'horizontal_flip' parameter(+)
3) After adding data augmentation and using the same batch size and steps per epoch, you noticed that each training epoch became a little slower than when you trained without it. Why?:
1. Because the image preprocessing takes cycles (+)
4) What does the fill_mode parameter do?:
3. It attempts to recreate lost information after a transformation like a shear(+)
5) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk:
3. Nothing, all augmentation is done in-memory(+)
6) How does Image Augmentation help solve overfitting?:
2. It manipulates the training set to generate more scenarios for features in the images (+)
7) When using Image Augmentation my training gets:
1. Slower (+)
8) Using Image Augmentation effectively simulates having a larger data set for training:
1. False
2. True (+)

Week3(c2): "Transfer Learning" (Convolutional Neural Networks in TensorFlow)

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W3L1_transfer_learning_cats_and_dogs_filtered.ipynb
---------------------------------------------------------------
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras import layers
local_weights_file = '/tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'
pre_trained_model = InceptionV3(input_shape = (150, 150, 3),
                                include_top = False,
                                weights = None)
pre_trained_model.load_weights(local_weights_file)
# Freeze the weights of the layers.
for layer in pre_trained_model.layers:
  layer.trainable = False
pre_trained_model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Choose `mixed7` as the last layer of your base model
last_layer = pre_trained_model.get_layer('mixed7')
print('last layer output shape', last_layer.output_shape)
last_output = last_layer.output
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Add dense layers for your classifier
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras import Model
# Flatten the output layer to 1 dimension
x = layers.Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = layers.Dense(1024, activation='relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = layers.Dense(1, activation='sigmoid')(x)
# Append the dense network to the base model
model = Model(pre_trained_model.input, x)
model.summary()
<<<<<<< HEAD

model.compile(optimizer=RMSprop(learning_rate=0.0001),
              loss = 'binary_crossentropy',
              metrics = ['accuracy'])

=======
model.compile(optimizer=RMSprop(learning_rate=0.0001),
              loss = 'binary_crossentropy',
              metrics = ['accuracy'])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
train_datagen = ImageDataGenerator(rescale = 1./255.,
                                   rotation_range = 40,
                                   width_shift_range = 0.2,
                                   height_shift_range = 0.2,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True  )
test_datagen = ImageDataGenerator(rescale = 1./255.)
train_generator = train_datagen.flow_from_directory(train_dir,
                                                    batch_size = 20,
                                                    class_mode = 'binary',
                                                    target_size = (150, 150) )
validation_generator = test_datagen.flow_from_directory(validation_dir,
                                                        batch_size = 20,
                                                        class_mode = 'binary',
                                                        target_size = (150, 150) )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
history = model.fit(
    train_generator,
    validation_data = validation_generator,
    steps_per_epoch = 100,
    epochs = 20,
    validation_steps = 50,
    verbose =1)
<<<<<<< HEAD

# Evaluate the results

======= # Evaluate the results >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

InceptionV3: is a popular deep neural network model for image classification. It is a convolutional neural network architecture that was developed by Google researchers as part of the larger Inception family of models.
When include_top=False: is set in a pre-trained model like InceptionV3, it means that the model's final fully connected layers, which are responsible for classification, are excluded.
When layer.trainable = False: is set for a specific layer in a neural network model, it means that the parameters of that layer will not be updated or trained during the training process. The layer will remain frozen or fixed, and its weights will remain unchanged.

=======

InceptionV3: is a popular deep neural network model for image classification. It is a convolutional neural network architecture that was developed by Google researchers as part of the larger Inception family of models.
When include_top=False: is set in a pre-trained model like InceptionV3, it means that the model's final fully connected layers, which are responsible for classification, are excluded.
When layer.trainable = False: is set for a specific layer in a neural network model, it means that the parameters of that layer will not be updated or trained during the training process. The layer will remain frozen or fixed, and its weights will remain unchanged.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W3LwAssignment_TransferLearning_Horses_Humans.ipynb
---------------------------------------------------------------
from tensorflow.keras.applications.inception_v3 import InceptionV3
local_weights_file = './tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'
def create_pre_trained_model(local_weights_file):
  pre_trained_model = InceptionV3(input_shape = (150, 150, 3),
                                  include_top = False,
                                  weights = None)
  pre_trained_model.load_weights(local_weights_file)
  for layer in pre_trained_model.layers:
    layer.trainable = False
  return pre_trained_model
<<<<<<< HEAD

pre_trained_model = create_pre_trained_model(local_weights_file)
pre_trained_model.summary()

=======
pre_trained_model = create_pre_trained_model(local_weights_file)
pre_trained_model.summary()
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def train_val_generators(TRAINING_DIR, VALIDATION_DIR):
  train_datagen = ImageDataGenerator(
      rescale = 1. / 255.,
      rotation_range = 40,
      width_shift_range = 0.2,
      height_shift_range = 0.2,
      shear_range = 0.2,
      zoom_range = 0.2,
      horizontal_flip = True  )
  train_generator = train_datagen.flow_from_directory(directory=TRAINING_DIR,
                                                      batch_size=32,
                                                      class_mode='binary',
                                                      target_size=(150, 150) )
  validation_datagen = ImageDataGenerator(rescale = 1./255.)flow_from_directory method
  validation_generator = validation_datagen.flow_from_directory(directory=VALIDATION_DIR,
                                                                batch_size=32,
                                                                class_mode='binary',
                                                                target_size=(150, 150) )
  return train_generator, validation_generator
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if (logs.get('accuracy') > 0.999):
      print("\nReached 99.9% accuracy so cancelling training!")
      self.model.stop_training = True
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def output_of_last_layer(pre_trained_model):
  last_desired_layer = pre_trained_model.get_layer('mixed7')
  print('last layer output shape: ', last_desired_layer.output_shape)
  last_output = last_desired_layer.output
  print('last layer output: ', last_output)
  return last_output
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_final_model(pre_trained_model, last_output):
  x = layers.Flatten()(last_output)
  x = layers.Dense(1024, activation='relu')(x)
  x = layers.Dropout(0.2)(x)
  x = layers.Dense(1, activation='sigmoid')(x)
  model = Model(inputs=pre_trained_model.input, outputs=x)
  model.compile(optimizer = RMSprop(learning_rate=0.0001),
                loss = 'binary_crossentropy',
                metrics = ['accuracy'])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = create_final_model(pre_trained_model, last_output)
total_params = model.count_params()
num_trainable_params = sum([w.shape.num_elements() for w in model.trainable_weights])
print(f"There are {total_params:,} total parameters in this model.")
print(f"There are {num_trainable_params:,} trainable parameters in this model.")
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
callbacks = myCallback()
history = model.fit(train_generator,
                    validation_data = validation_generator,
                    epochs = 100,
                    verbose = 2,
                    callbacks = callbacks)
<<<<<<< HEAD

# Plot the training and validation accuracies for each epoch

======= # Plot the training and validation accuracies for each epoch >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 3 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1)If I put a dropout parameter of 0.2, how many nodes will I lose?:
1. 20% of them (+)
2) Why is transfer learning useful?:
3. Because I can use the features that were learned from large datasets that I may not have access to(+ -)
3) How did you lock or freeze a layer from retrainig?:
4. layer.trainable = false (+)
4) How do you change the number of classes the model can classify when using transfer learning?(i.e. the original model handled 1000 classes, but yours handles just 2):
3. When you add your DNN at the bottom of the network, you specify your output layer with the number of classes you want(+)
5) Can you use Image Augmentation with Transfer Learning Models?:
2. Yes, because you are adding new layers at the bottom of the network, and you can use image augmentation when training these(+)
6) Why do dropouts help avoid overfitting?:
1. Because neighbor neurons can have similar weights, and this can skew the final training(+)
7) What would the symptom of a Dropout rate being set too nigh?:
1. The network would lose specialization to the effect that it would be inefficient of ineffective at learning, driving accuracy down (+)
8) Which is the correct line of code for adding Dropout of 20% of neurons using TensorFlow:
3. tf.keras.layers.Dropout(0.2) (+)

Week4(c2): "Multiclass Classifications" (Convolutional Neural Networks in TensorFlow)

=======

Week 3 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1)If I put a dropout parameter of 0.2, how many nodes will I lose?:
1. 20% of them (+)
2) Why is transfer learning useful?:
3. Because I can use the features that were learned from large datasets that I may not have access to(+ -)
3) How did you lock or freeze a layer from retrainig?:
4. layer.trainable = false (+)
4) How do you change the number of classes the model can classify when using transfer learning?(i.e. the original model handled 1000 classes, but yours handles just 2):
3. When you add your DNN at the bottom of the network, you specify your output layer with the number of classes you want(+)
5) Can you use Image Augmentation with Transfer Learning Models?:
2. Yes, because you are adding new layers at the bottom of the network, and you can use image augmentation when training these(+)
6) Why do dropouts help avoid overfitting?:
1. Because neighbor neurons can have similar weights, and this can skew the final training(+)
7) What would the symptom of a Dropout rate being set too nigh?:
1. The network would lose specialization to the effect that it would be inefficient of ineffective at learning, driving accuracy down (+)
8) Which is the correct line of code for adding Dropout of 20% of neurons using TensorFlow:
3. tf.keras.layers.Dropout(0.2) (+)

Week4(c2): "Multiclass Classifications" (Convolutional Neural Networks in TensorFlow)

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W4L1_MultiClassifier_Rock_Paper_Scissors.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(150, 150, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax') ])
model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Set the training parameters
model.compile(loss = 'categorical_crossentropy',
              optimizer = 'rmsprop',
              metrics = ['accuracy'] )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.image import ImageDataGenerator
TRAINING_DIR = './tmp/rps-train/rps'
VALIDATION_DIR = './tmp/rps-test/rps-test-set'
training_datagen = ImageDataGenerator(
    rescale = 1./255.,
    rotation_range = 40,
    width_shift_range = 0.2,
    height_shift_range = 0.2,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
    fill_mode = 'nearest')
validation_datagen = ImageDataGenerator(rescale = 1./255.)
train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size = (150, 150),
    class_mode = 'categorical',
    batch_size = 126 )
validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size = (150, 150),
    class_mode = 'categorical',
    batch_size = 126 )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
history = model.fit(
    train_generator,
    epochs = 25,
    steps_per_epoch = 20,
    validation_data = validation_generator,
    verbose = 1,
    validation_steps = 3 )
<<<<<<< HEAD

# Plot the results

=======
# Plot the results
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Model Prediction  [paper, rock, scissors]
import numpy as np
from google.colab import files
from tensorflow.keras.utils import load_img, img_to_array
uploaded = files.upload()
for fn in uploaded.keys():
  path = fn
  img = load_img(path, target_size=(150, 150))
  x = img_to_array(img)
  x = np.expand_dims(x, axis=0)
  images = np.vstack([x])
  classes = model.predict(images, batch_size=10)
  print(fn)
  print(classes)

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= # Plot the chart for accuracy and loss on both training and validation --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C2W4LwAssignment_MultiClassification_26LettersOfTheEnglishAlphabetCSV.ipynb
---------------------------------------------------------------
def parse_data_from_input(filename):
  with open(filename) as file:
    csv_reader = csv.reader(file, delimiter=',')
    next(csv_reader)
    data = []
    for row in csv_reader:
      label = float(row[0])
      image_pixels = [float(x) for x in row[1:]]
      image = np.array(image_pixels).reshape(28, 28)
      data.append((label, image))
    labels, images = zip(*data)
    labels = np.array(labels, dtype=np.float64)
    images = np.array(images, dtype=np.float64)
    return images, labels
<<<<<<< HEAD

# Plot a sample of 10 images from the training set

=======
# Plot a sample of 10 images from the training set
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def train_val_generators(training_images, training_labels, validation_images, validation_labels):  
  num = 26
  training_images = np.expand_dims(training_images, -1)
  validation_images = np.expand_dims(validation_images, -1)
  train_datagen = ImageDataGenerator(rescale = 1./255.,
                                       zoom_range=0.2)
  train_generator = train_datagen.flow(x = training_images,
                                      #  y = training_labels,
                                       y=tf.keras.utils.to_categorical(training_labels, num_classes=num),
                                       batch_size = 32)
  validation_datagen = ImageDataGenerator(rescale = 1./255.)
  validation_generator = validation_datagen.flow(x = validation_images,
                                                #  y = validation_labels,                                                 
                                                 y=tf.keras.utils.to_categorical(validation_labels, num_classes=num),
                                                 batch_size=32)
  return train_generator, validation_generator
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model():
  model = tf.keras.models.Sequential([
      tf.keras.layers.Conv2D(52, (3, 3), activation='relu', input_shape=(28, 28, 1)),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Conv2D(52, (3, 3), activation='relu'),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(512, activation='relu'),
      tf.keras.layers.Dense(512, activation='relu'),
      tf.keras.layers.Dense(26, activation='softmax')  ])
  model.compile(optimizer = 'rmsprop',
                loss = 'categorical_crossentropy',
                metrics = ['accuracy'])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = create_model()
history = model.fit(train_generator,
                    epochs=15,
                    validation_data = validation_generator)
<<<<<<< HEAD

# Plot the chart for accuracy and loss on both training and validation


======= # Plot the chart for accuracy and loss on both training and validation >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

class_mode='binary' -> class_mode='categorical' (train_generator)
layers.Dense(1, activation='sigmoid') -> layers.Dense(3, activation='softmax') (model)
loss = 'binary_crossentropy' -> loss = 'categorical_crossentropy' (model.compile)
---------------
Week 4 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1) The diagram for traditional programming had Rules and Data In, but what came out?:
1. Answers (+)
2) Why does the DNN for Fashion MNIST have 10 output neurons?:
4. The dataset has 10 classes(+)
3)What is a Convolution?:
3. A technique to extract features from an image(+)
4) Applying Convolutions on top of a DNN will have what impact on training?:
4. It depends on many factors. It might make your training faster of slower, and a poorly designed Convolytiional layer may even be less efficient than a lain DNN(+)
5) What method on an ImageGenerator is used to normalize the image?:
4. rescale (+)
6) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk.:
3. Nothing (+)
7) Can you use Image augmentation with Transfer Learning?:
2. Yes. It's pre-trained layers that are frozen. So you can augment your images as you train the bottom layers of the DNN with them (+)
8) When training for multiple classes what is the Class Mode for Image Augmentation?:
3. class_mode = 'categorical'(+)

3) Natural Language Processing in TensorFlow (13.MLg_title)

Week1(c3): "Sentiment in text"

======= # Plot the chart for accuracy and loss on both training and validation -->

class_mode='binary' -> class_mode='categorical' (train_generator)
layers.Dense(1, activation='sigmoid') -> layers.Dense(3, activation='softmax') (model)
loss = 'binary_crossentropy' -> loss = 'categorical_crossentropy' (model.compile)
---------------
Week 4 Quiz(c2): (Convolutional Neural Networks in TensorFlow)
1) The diagram for traditional programming had Rules and Data In, but what came out?:
1. Answers (+)
2) Why does the DNN for Fashion MNIST have 10 output neurons?:
4. The dataset has 10 classes(+)
3)What is a Convolution?:
3. A technique to extract features from an image(+)
4) Applying Convolutions on top of a DNN will have what impact on training?:
4. It depends on many factors. It might make your training faster of slower, and a poorly designed Convolytiional layer may even be less efficient than a lain DNN(+)
5) What method on an ImageGenerator is used to normalize the image?:
4. rescale (+)
6) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk.:
3. Nothing (+)
7) Can you use Image augmentation with Transfer Learning?:
2. Yes. It's pre-trained layers that are frozen. So you can augment your images as you train the bottom layers of the DNN with them (+)
8) When training for multiple classes what is the Class Mode for Image Augmentation?:
3. class_mode = 'categorical'(+)

3) Natural Language Processing in TensorFlow (13.MLg_title)

Week1(c3): "Sentiment in text"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W1L1_Tokenizer_Basics.ipynb
---------------------------------------------------------------
from tensorflow.keras.preprocessing.text import Tokenizer
sentences =[
    'i love my dog',
    'I love my cat:']
tokenizer = Tokenizer(num_words = 100)
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
print(word_index)
{'i': 1, 'love': 2, 'my': 3, 'dog': 4, 'cat': 5}

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W1L2_Generating_Sequences_Padding.ipynb
---------------------------------------------------------------
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
sentences = [
    'I love my dog',
    'I, love my cat',
    'You love my dog',
    'Do you think my dog is amazing?']
tokenizer = Tokenizer(num_words = 100, oov_token = '<OOV>')
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
sequences = tokenizer.texts_to_sequences(sentences)
padded = pad_sequences(sequences, maxlen=5)
print("\nWord Index = ", word_index)
print("\nSequences = ", sequences)
Word Index =  {'<OOV>': 1, 'my': 2, 'love': 3, 'dog': 4, 'i': 5, 'you': 6, 'cat': 7, 'do': 8, 'think': 9, 'is': 10, 'amazing': 11}
Sequences =  [[5, 3, 2, 4], [5, 3, 2, 7], [6, 3, 2, 4], [8, 6, 9, 2, 4, 10, 11]]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
print("\nPadded Sequences:")
print(padded)
Padded Sequences:
[[ 0  5  3  2  4]
 [ 0  5  3  2  7]
 [ 0  6  3  2  4]
 [ 9  2  4 10 11]]

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W1L3_sarcasm_detection.ipynb
---------------------------------------------------------------
import json
with open("./sarcasm.json", 'r') as f:
  datastore = json.load(f)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
sentences = []
labels = []
urls = []
for item in datastore:
  sentences.append(item['headline'])
  labels.append(item['is_sarcastic'])
  urls.append(item['article_link'])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(oov_token="<OOV>")
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
print(f"number of words in word_index: {len(word_index)}")
print(f"word_index: {word_index}")
print()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
sequences = tokenizer.texts_to_sequences(sentences)
padded = pad_sequences(sequences, padding='post')
index = 2
print(f"sample headline: {sentences[index]}")
print(f"padded sequence: {padded[index]}")
print()
print(f"shape of padded sequences: {padded.shape}")
<<<<<<< HEAD

number of words in word_index: 29657
word_index: {'<OOV>': 1, 'to': 2, 'of': 3, 'the': 4, 'in': 5, 'for': 6, ...

=======
number of words in word_index: 29657
word_index: {'<OOV>': 1, 'to': 2, 'of': 3, 'the': 4, 'in': 5, 'for': 6, ...
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
sample headline: mom starting to fear sons web series closest thing she will have to grandchild
padded sequence: [  145   838     2   907  1749  2093   582  4719   221   143    39    46
     2 10736     0     0     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0     0     0     0     0
     0     0     0     0]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from google.colab import runtime
stop_runtime = input("Stop runtime('y' or 'n'): ")
if stop_runtime == 'y':
  runtime.unassign()

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W1LwAssignment_BBC_News_archive.ipynb
---------------------------------------------------------------
def remove_stopwords(sentence):
  stopwords = ["a", "about", "above", "after", "again"...
  sentence = sentence.lower()
  words = sentence.split()
  filtered_words = [word for word in words if word not in stopwords]
  sentece = " ".join(filtered_words)
  return sentece
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def parse_data_from_file(filename):
  sentences = []
  labels = []
  with open(filename, 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    next(reader)
    for row in reader:
      label = row[0]
      sentence = remove_stopwords(row[1])
      sentences.append(sentence)
      labels.append(label)
  return sentences, labels
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def fit_tokenizer(sentences):
  tokenizer = Tokenizer(oov_token='<OOV>')
  tokenizer.fit_on_texts(sentences)
  return tokenizer
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def get_padded_sequences(tokenizer, sentences):
  sequences = tokenizer.texts_to_sequences(sentences)
  padded_sequences = pad_sequences(sequences, padding='post')
  return padded_sequences
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def tokenize_labels(labels):
  label_tokenizer = Tokenizer()
  label_tokenizer.fit_on_texts(labels)
  label_word_index = label_tokenizer.word_index
  label_sequences = label_tokenizer.texts_to_sequences(labels)
  return label_sequences, label_word_index
<<<<<<< HEAD

label_sequences, label_word_index = tokenize_labels(labels)
print(f"Vocabulary of labels looks like this {label_word_index}\n")
print(f"First ten sequences {label_sequences[:10]}\n")

Vocabulary of labels looks like this {'sport': 1, 'business': 2, 'politics': 3, 'tech': 4, 'entertainment': 5}
First ten sequences [[4], [2], [1], [1], [5], [3], [3], [1], [1], [5]]

=======
label_sequences, label_word_index = tokenize_labels(labels)
print(f"Vocabulary of labels looks like this {label_word_index}\n")
print(f"First ten sequences {label_sequences[:10]}\n")
Vocabulary of labels looks like this {'sport': 1, 'business': 2, 'politics': 3, 'tech': 4, 'entertainment': 5}
First ten sequences [[4], [2], [1], [1], [5], [3], [3], [1], [1], [5]]
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from google.colab import runtime
stop_runtime = input("Stop runtime('y' or 'n'): ")
if stop_runtime == 'y':
  runtime.unassign()

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

The .fit_on_texts(): function is used to create a vocabulary index based on the frequency of words in a given text corpus.
The .word_index: attribute returns a dictionary that maps words to their corresponding integer indices.
The .texts_to_sequences(): function is used to convert a list of texts into a list of sequences, where each sequence represents the corresponding text as a sequence of integers based on the word indices.

Week 1 Quiz(c3): (Natural Language Processing in TensorFlow)
1) What is the name of the object used to tokenize sentences?:
2. Tokenizer (+)
2)What is the name of the method used to tokenize a list of sentences?:
1. fit_on_texts(sentences) (+)
3) Once you have the corpus tokenises, what's the method used to encode a list of sentences to use those tokens?:
1. texts_to_sequences(sentences) (+)
4) When initializing the tokenizer, how do you specify a token to use for unknown words?:
1. oov_token=<Token> (+)
5) If you don't use a token for out of vocabulary words, what happens at encoding?:
4. The word isn't encoded, and is skipped in the sequence (+)
6) If you have a number of sequences of different lengths, how do you ensure that hey are understood when fed into a neural network?:
2. Use the pad_sequences function from the tensorflow.keras.preprocessing.sequence namespace (+)
7) If you have a number of sequences of different length, and call pad_sequences on them, that's the default result?:
2. They'll get padded to the length of the longest sequence by adding zeros to the beginning of shorter ones (+)
8) When padding sequences, if you want the padding to be at the end of the sequence, how do you do it?:
2. Pass padding='post' to pad_sequences when initializing it (+)

Week2(c3): "Word Embeddings" (Natural Language Processing in TensorFlow)

=======

The .fit_on_texts(): function is used to create a vocabulary index based on the frequency of words in a given text corpus.
The .word_index: attribute returns a dictionary that maps words to their corresponding integer indices.
The .texts_to_sequences(): function is used to convert a list of texts into a list of sequences, where each sequence represents the corresponding text as a sequence of integers based on the word indices.

Week 1 Quiz(c3): (Natural Language Processing in TensorFlow)
1) What is the name of the object used to tokenize sentences?:
2. Tokenizer (+)
2)What is the name of the method used to tokenize a list of sentences?:
1. fit_on_texts(sentences) (+)
3) Once you have the corpus tokenises, what's the method used to encode a list of sentences to use those tokens?:
1. texts_to_sequences(sentences) (+)
4) When initializing the tokenizer, how do you specify a token to use for unknown words?:
1. oov_token=<Token> (+)
5) If you don't use a token for out of vocabulary words, what happens at encoding?:
4. The word isn't encoded, and is skipped in the sequence (+)
6) If you have a number of sequences of different lengths, how do you ensure that hey are understood when fed into a neural network?:
2. Use the pad_sequences function from the tensorflow.keras.preprocessing.sequence namespace (+)
7) If you have a number of sequences of different length, and call pad_sequences on them, that's the default result?:
2. They'll get padded to the length of the longest sequence by adding zeros to the beginning of shorter ones (+)
8) When padding sequences, if you want the padding to be at the end of the sequence, how do you do it?:
2. Pass padding='post' to pad_sequences when initializing it (+)

Week2(c3): "Word Embeddings" (Natural Language Processing in TensorFlow)

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W2L1_IMDB_Reviews_Dataset.ipynb
---------------------------------------------------------------
train_data, test_data = imdb['train'], imdb['test']
training_sentences = []
training_labels = []
testing_sentences = []
testing_labels = []
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
for s,l in train_data:
  training_sentences.append(s.numpy().decode('utf8'))
  training_labels.append(l.numpy())
for s,l in test_data:
  testing_sentences.append(s.numpy().decode('utf8'))
  testing_labels.append(l.numpy())
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Parameters
vocab_size = 10000
max_length = 150
embedding_dim = 16
trunc_type = 'post'
oov_tok = "<OOV>"
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)
tokenizer.fit_on_texts(training_sentences)
word_index = tokenizer.word_index
sequences = tokenizer.texts_to_sequences(training_sentences)
padded = pad_sequences(sequences, maxlen=max_length, truncating=trunc_type)
testing_sequences = tokenizer.texts_to_sequences(testing_sentences)
testing_padded = pad_sequences(testing_sequences, maxlen=max_length, truncating=trunc_type)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Flatten(),
    # tf.keras.layers.Dense(6, activation='relu'),
    tf.keras.layers.Dense(1, activation='relu'),
    tf.keras.layers.Dense(3, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
num_epochs = 10
model.fit(padded,
          training_labels_final,
          epochs=num_epochs,
          validation_data=(testing_padded, testing_labels_final))
<<<<<<< HEAD

# Visualize Word Embeddings
files.download('vecs.tsv')
files.download('meta.tsv')

=======
# Visualize Word Embeddings
files.download('vecs.tsv')
files.download('meta.tsv')
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from google.colab import runtimestop_runtime = input("Stop runtime('y' or 'n'): ")
if stop_runtime == 'y':
  runtime.unassign()

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

The pad_sequences(): function is used to pad or truncate sequences to a specified length, ensuring that all sequences have the same length for efficient processing in machine learning models.
The .Embedding(): function typically refers to embedding a data representation into a lower-dimensional space. In the context of natural language processing (NLP), it is commonly used to convert textual data into numerical vectors. This technique brings the advantage of capturing and representing semantic relationships between words or sentences.

=======

The pad_sequences(): function is used to pad or truncate sequences to a specified length, ensuring that all sequences have the same length for efficient processing in machine learning models.
The .Embedding(): function typically refers to embedding a data representation into a lower-dimensional space. In the context of natural language processing (NLP), it is commonly used to convert textual data into numerical vectors. This technique brings the advantage of capturing and representing semantic relationships between words or sentences.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W2L2_Sarcasm_Dataset_binary_classifier.ipynb
---------------------------------------------------------------
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
trunc_type = 'post'
padding_type = 'post'
oov_tok = "<OOV>"
tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)
tokenizer.fit_on_texts(training_sentences)
word_index = tokenizer.word_index
training_sequences = tokenizer.texts_to_sequences(training_sentences)
training_padded = pad_sequences(training_sequences, maxlen=max_length)
testing_sequences = tokenizer.texts_to_sequences(testing_sentences)
testing_padded = pad_sequences(testing_sequences,
                               maxlen=max_length,
                               padding=padding_type,
                               truncating=trunc_type)
training_labels = np.array(training_labels)
testing_labels = np.array(testing_labels)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.GlobalAveragePooling1D(),
    tf.keras.layers.Dense(24, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid') ])
model.summary()
<<<<<<< HEAD

model.compile(loss='binary_crossentropy', 
              optimizer='adam', 
              metrics=['accuracy'])

=======
model.compile(loss='binary_crossentropy', 
              optimizer='adam', 
              metrics=['accuracy'])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
num_epochs = 30
history = model.fit(training_padded,
                    training_labels,
                    epochs=num_epochs,
                    validation_data=(testing_padded, testing_labels),
                    verbose=1)
<<<<<<< HEAD

# Visualize the Results
# Plot utility

=======
# Visualize the Results
# Plot utility
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Visualize Word Embeddings
files.download('vesc_c3w2l2.tsv')
files.download('meta_c3w2l2.tsv')

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W2L3_Subword_Tokenization_IMDB_Dataset.ipynb
---------------------------------------------------------------
train_data = imdb_plaintext['train']
training_sentences = []
for s,_ in train_data:
  training_sentences.append(s.numpy().decode('utf8'))
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
vocab_size = 10000
oov_tok = '<OOV>'
tokenizer_plaintext = Tokenizer(num_words=vocab_size, oov_token=oov_tok)sentences
tokenizer_plaintext.fit_on_texts(training_sentences)
sequences = tokenizer_plaintext.texts_to_sequences(training_sentences)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
BUFFER_SIZE = 10000
BATCH_SIZE = 64
train_data, test_data = imdb_subwords['train'], imdb_subwords['test']
train_dataset = train_data.shuffle(BUFFER_SIZE)
train_dataset = train_dataset.padded_batch(BATCH_SIZE)
test_dataset = test_data.padded_batch(BATCH_SIZE)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
import tensorflow as tf
embedding_dim = 64
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(tokenizer_subwords.vocab_size, embedding_dim),
    tf.keras.layers.GlobalAveragePooling1D(),
    tf.keras.layers.Dense(6, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
num_epochs = 10
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
history = model.fit(train_dataset,
                    epochs=num_epochs,
                    validation_data=test_dataset)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Visualize the results
# Plot utility

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

.GlobalAveragePooling1D(): is a pooling layer in deep learning models that is typically used in natural language processing (NLP) tasks. It performs global average pooling operation along the temporal dimension of the input data. This operation reduces the sequence dimension to a fixed-dimensional vector, irrespective of the input sequence length.
.padded_batch(): is a function used to create batches of data with sequences of variable lengths by padding or truncating the sequences to a fixed length within each batch.

=======

.GlobalAveragePooling1D(): is a pooling layer in deep learning models that is typically used in natural language processing (NLP) tasks. It performs global average pooling operation along the temporal dimension of the input data. This operation reduces the sequence dimension to a fixed-dimensional vector, irrespective of the input sequence length.
.padded_batch(): is a function used to create batches of data with sequences of variable lengths by padding or truncating the sequences to a fixed length within each batch.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W2Lw_Diving_deeper_into_BBC_News.ipynb
---------------------------------------------------------------
def remove_stopwords(sentence):
  stopwords = ["a", "about", "above", "after", "again", ...
  sentence = sentence.lower()
  words = sentence.split()
  no_words = [w for w in words if w not in stopwords]
  sentence = " ".join(no_words)
  return sentence
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def parse_data_from_file(filename):
  sentences = []
  labels = []
  with open(filename, 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    next(reader)
    for row in reader:
      labels.append(row[0])
      sentence = row[1]
      sentence = remove_stopwords(sentence)
      sentences.append(sentence)
  return sentences, labels
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def train_val_split(sentences, lables, training_split):
  train_size = int(int(len(sentences))*training_split)
  train_sentences = sentences[:train_size]
  train_labels = labels[:train_size]
  validation_sentences = sentences[train_size:]
  validation_labels = labels[train_size:]
  return train_sentences, validation_sentences, train_labels, validation_labels
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def fit_tokenizer(train_sentences, num_words, oov_token):
  tokenizer = Tokenizer(num_words=num_words, oov_token=oov_token)
  tokenizer.fit_on_texts(train_sentences)
  return tokenizer
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def seq_and_pad(sentences, tokenizer, padding, maxlen):
  sequences = tokenizer.texts_to_sequences(sentences)
  padded_sequences = pad_sequences(sequences, padding=padding, maxlen=maxlen)
  return padded_sequences
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def tokenize_labels(all_labels, split_labels):
  label_tokenizer = Tokenizer(lower=True, oov_token=None)
  label_tokenizer.fit_on_texts(all_labels)
  label_seq = label_tokenizer.texts_to_sequences(split_labels)
  label_seq_np = np.array(label_seq) - 1
  return label_seq_np
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model(num_words, embedding_dim, maxlen):
  tf.random.set_seed(123)
  model = tf.keras.Sequential([
      tf.keras.layers.Embedding(num_words, embedding_dim, input_length=maxlen),
      tf.keras.layers.GlobalAveragePooling1D(),
      tf.keras.layers.Dense(5, activation='relu'),
      tf.keras.layers.Dense(10, activation='softmax')  ])
  model.compile(loss='sparse_categorical_crossentropy',
                optimizer='adam',
                metrics=['accuracy'])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = create_model(NUM_WORDS, EMBEDDING_DIM, MAXLEN)
history = model.fit(train_padded_seq, 
                    train_labels_seq, 
                    epochs=30, 
                    validation_data=(val_padded_seq, val_labels_seq))
<<<<<<< HEAD

plot_graphs(history, "accuracy")
plot_graphs(history, "loss")

=======
plot_graphs(history, "accuracy")
plot_graphs(history, "loss")
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Optional Exercise - Visualizing 3D Vectors
files.download('vecs_c3w2lw.tsv')
files.download('meta_c3w2lw.tsv')

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 2 Quiz(c3): (Natural Language Processing in TensorFlow)
1) what is the name of the TensorFlow library containing common data that you can use to train and test neural networks?:
4. TensorFlow Datasets (+)
2) How many reviews are there is the IMDB dataset and how are they split?:
3. 50,000 records, 50/50 train/test split (- +)
3) How are the labels for the IMDB dataset encoded? in Python:
1. Reviews encoded as a number 0-1 (+)
4) What is the purpose of the embedding dimension?:
4. It is the number of dimensions for the vector representing the word encoding (+)
5) When tokenizing a corpus, what does the num_words=n parameter do?:
1. It specifies the maximum number of words to be tokenized, and picks the most common 'n-1' words(+)
6) To use word embeddings in TensorFlow, in a sequential layer, what is the name of the class?:
3. tf.keras.layers.Embedding (+)
7) IMDB Reviews are either positive of negative. What type of loss function should be used in this scenario?:
4. Binary crossentropy (+)
8) When using IMDB Sub Words Dataset, our results in classification were poor. Why?:
3. Sequence becomes much more important when dealing with subwords, but we're ignoring word positions (+)

Week3(c3): "Assessments Overdue" (Natural Language Processing in TensorFlow)
.Bidirectional(): is a function or layer commonly used in recurrent neural networks (RNNs) and sequence modeling tasks. It creates a bidirectional version of the specified RNN layer, which means that it processes input sequences in both forward and backward directions. This allows the model to capture information from past and future context simultaneously, which can be beneficial in tasks such as natural language processing or time-series analysis.
.Conv1D(): is a function or layer used in convolutional neural networks (CNNs) for one-dimensional input data. It performs a one-dimensional convolution operation on the input data, applying a set of learnable filters to extract local patterns or features.
.GlobalMaxPooling1D(): is a pooling layer commonly used in deep learning models for natural language processing (NLP) tasks. It performs max pooling operation along the temporal dimension of the input data, reducing the sequence length to a fixed-dimensional vector by taking the maximum value from each feature across the entire sequence.
.GRU(): is a type of recurrent neural network (RNN) layer called Gated Recurrent Unit, which is commonly used for sequence modeling tasks. It processes input sequences and captures long-term dependencies by using a gating mechanism that allows the network to selectively remember or forget information from previous time steps.
EMBEDDING_DIM: Dimension of the dense embedding, will be used in the embedding layer of the model. Defaults to 100.
MAXLEN: Maximum length of all sequences. Defaults to 16.
TRUNCATING: Truncating strategy (truncate either before or after each sequence.). Defaults to 'post'.
PADDING: Padding strategy (pad either before or after each sequence.). Defaults to 'post'.
OOV_TOKEN: Token to replace out-of-vocabulary words during text_to_sequence calls. Defaults to "<OOV>".
MAX_EXAMPLES: Max number of examples to use. Defaults to 160000 (10% of the original number of examples)
TRAINING_SPLIT: Proportion of data used for training.

=======

Week 2 Quiz(c3): (Natural Language Processing in TensorFlow)
1) what is the name of the TensorFlow library containing common data that you can use to train and test neural networks?:
4. TensorFlow Datasets (+)
2) How many reviews are there is the IMDB dataset and how are they split?:
3. 50,000 records, 50/50 train/test split (- +)
3) How are the labels for the IMDB dataset encoded? in Python:
1. Reviews encoded as a number 0-1 (+)
4) What is the purpose of the embedding dimension?:
4. It is the number of dimensions for the vector representing the word encoding (+)
5) When tokenizing a corpus, what does the num_words=n parameter do?:
1. It specifies the maximum number of words to be tokenized, and picks the most common 'n-1' words(+)
6) To use word embeddings in TensorFlow, in a sequential layer, what is the name of the class?:
3. tf.keras.layers.Embedding (+)
7) IMDB Reviews are either positive of negative. What type of loss function should be used in this scenario?:
4. Binary crossentropy (+)
8) When using IMDB Sub Words Dataset, our results in classification were poor. Why?:
3. Sequence becomes much more important when dealing with subwords, but we're ignoring word positions (+)

Week3(c3): "Assessments Overdue" (Natural Language Processing in TensorFlow)
.Bidirectional(): is a function or layer commonly used in recurrent neural networks (RNNs) and sequence modeling tasks. It creates a bidirectional version of the specified RNN layer, which means that it processes input sequences in both forward and backward directions. This allows the model to capture information from past and future context simultaneously, which can be beneficial in tasks such as natural language processing or time-series analysis.
.Conv1D(): is a function or layer used in convolutional neural networks (CNNs) for one-dimensional input data. It performs a one-dimensional convolution operation on the input data, applying a set of learnable filters to extract local patterns or features.
.GlobalMaxPooling1D(): is a pooling layer commonly used in deep learning models for natural language processing (NLP) tasks. It performs max pooling operation along the temporal dimension of the input data, reducing the sequence length to a fixed-dimensional vector by taking the maximum value from each feature across the entire sequence.
.GRU(): is a type of recurrent neural network (RNN) layer called Gated Recurrent Unit, which is commonly used for sequence modeling tasks. It processes input sequences and captures long-term dependencies by using a gating mechanism that allows the network to selectively remember or forget information from previous time steps.
EMBEDDING_DIM: Dimension of the dense embedding, will be used in the embedding layer of the model. Defaults to 100.
MAXLEN: Maximum length of all sequences. Defaults to 16.
TRUNCATING: Truncating strategy (truncate either before or after each sequence.). Defaults to 'post'.
PADDING: Padding strategy (pad either before or after each sequence.). Defaults to 'post'.
OOV_TOKEN: Token to replace out-of-vocabulary words during text_to_sequence calls. Defaults to "<OOV>".
MAX_EXAMPLES: Max number of examples to use. Defaults to 160000 (10% of the original number of examples)
TRAINING_SPLIT: Proportion of data used for training.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W3L1_LSTM_Single_Layer.ipynb
---------------------------------------------------------------
BUFFER_SIZE = 10000
BATCH_SIZE = 256
train_data, test_data = dataset['train'], dataset['test']
train_dataset = train_data.shuffle(BUFFER_SIZE)
train_dataset = train_dataset.padded_batch(BATCH_SIZE)
test_dataset = test_data.padded_batch(BATCH_SIZE)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
embedding_dim = 64
lstm_dim = 64
dense_dim = 64
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(tokenizer.vocab_size, embedding_dim),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(lstm_dim)),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model.summary()
<<<<<<< HEAD

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

=======
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
num_epochs = 10
history = model.fit(train_dataset,
                    epochs=num_epochs,
                    validation_data=test_dataset)
<<<<<<< HEAD

# Visualize the results

======= # Visualize the results >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W3L2_LSTM_Multiple.ipynb
---------------------------------------------------------------
embedding_dim = 64
lstm1_dim = 64
lstm2_dim = 32
dense_dim = 64
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(tokenizer.vocab_size, embedding_dim),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(lstm1_dim, return_sequences=True)),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(lstm2_dim)),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model.summary()
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
num_epochs = 10
history = model.fit(train_dataset,
                    epochs=num_epochs,
                    validation_data=test_dataset)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Plot the accuracy and results
plot_graphs(history, "accuracy")
plot_graphs(history, "loss")

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W3L3_CNN_Conv1D.ipynb
---------------------------------------------------------------
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(tokenizer.vocab_size, embedding_dim),
    tf.keras.layers.Conv1D(filters=filters, kernel_size=kernel_size, activation='relu'),
    tf.keras.layers.GlobalMaxPooling1D(),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model.summary()
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
num_epochs = 10
history = model.fit(train_dataset,
                    epochs=num_epochs,
                    validation_data=test_dataset)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Plot the accuracy and results
plot_graphs(history, "accuracy")
plot_graphs(history, "loss")

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W3L4_GRU_LSTM_Conv1D_imdb_reviews.ipynb
---------------------------------------------------------------
# Building Models for the IMDB Reviews Dataset
# Model 1: Flatten
embedding_dim = 16
dense_dim = 6
model_flatten = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model_flatten.compile(loss='binary_crossentropy',
                      optimizer='adam',
                      metrics=['accuracy'])
model_flatten.summary()
# Model 2: LSTM
model_lstm = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(lstm_dim)),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model_lstm.compile(loss='binary_crossentropy',
                   optimizer='adam',
                   metrics=['accuracy'])
model_lstm.summary()
# Model 3: GRU
embedding_dim = 16
gru_dim = 32
dense_dim = 6
model_gru = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Bidirectional(tf.keras.layers.GRU(gru_dim)),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model_gru.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
model_gru.summary()
# Model 4: Convolution
embedding_dim = 16
filters = 128
kernel_size = 5
dense_dim = 6
model_conv = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Conv1D(filters, kernel_size, activation='relu'),
    tf.keras.layers.GlobalAveragePooling1D(),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model_conv.compile(loss='binary_crossentropy',
                   optimizer='adam',
                   metrics=['accuracy'])
model_conv.summary()
# Model 5: Convolution, From C3W3L3_CNN_Conv1D
embedding_dim = 16
filters = 128
kernel_size = 5
dense_dim = 6
model_conv2 = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Conv1D(filters, kernel_size, activation='relu'),
    tf.keras.layers.GlobalMaxPooling1D(),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model_conv2.compile(loss='binary_crossentropy',
                   optimizer='adam',
                   metrics=['accuracy'])
model_conv.summary()

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W3L5_Sarcasm_with_Bidirectional_LSTM.ipynb
---------------------------------------------------------------
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
vocab_size = 10000
max_length = 120
trunc_type = 'post'
padding_type = 'post'
oov_tok = '<OOV>'
tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)
tokenizer.fit_on_texts(training_sentences)
word_index = tokenizer.word_index
training_sequences = tokenizer.texts_to_sequences(training_sentences)
training_padded = pad_sequences(training_sequences,
                                maxlen=max_length,
                                padding=padding_type,
                                truncating=trunc_type)
testing_sequences = tokenizer.texts_to_sequences(testing_sentences)
testing_padded = pad_sequences(testing_sequences,
                               maxlen=max_length,
                               padding=padding_type,
                               truncating=trunc_type)
training_labels = np.array(training_labels)
testing_labels = np.array(testing_labels)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
embedding_dim = 16
lstm_dim = 32
dense_dim = 24
model_lstm = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(lstm_dim)),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model_lstm.compile(loss='binary_crossentropy',
                   optimizer='adam',
                   metrics=['accuracy'])
model_lstm.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Plot the accuracy and loss history
plot_graphs(history_lstm, 'accuracy')
plot_graphs(history_lstm, 'loss')

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W3L6_sarcasm_1D_convolutional.ipynb
---------------------------------------------------------------
embedding_dim = 16
filters = 128
kernel_size = 5
dense_dim = 6
model_conv = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
    tf.keras.layers.Conv1D(filters, kernel_size, activation='relu'),
    tf.keras.layers.GlobalMaxPooling1D(),
    tf.keras.layers.Dense(dense_dim, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')])
model_conv.compile(loss='binary_crossentropy', 
                   optimizer='adam', 
                   metrics=['accuracy'])
model_conv.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Plot the accuracy and loss history
plot_graphs(history_conv, 'accuracy')
plot_graphs(history_conv, 'loss')

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W3Lw_Overfitting_NLP_Sentiment140dataset.ipynb
---------------------------------------------------------------
# Using pre-defined Embeddings
GLOVE_FILE ='./data/glove.6B.100d.txt'
GLOVE_EMBEDDINGS = {}
with open(GLOVE_FILE) as f:
  for line in f:
    values = line.split()
    word = values[0]
    coefs = np.asarray(values[1:], dtype='float32')
    GLOVE_EMBEDDINGS[word] = coefs
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Represent the words in your vocabulary using the embeddings
EMBEDDINGS_MATRIX = np.zeros((VOCAB_SIZE+1, EMBEDDING_DIM))
for word, i in word_index.items():
  embedding_vector = GLOVE_EMBEDDINGS.get(word)
  if embedding_vector is not None:
    EMBEDDINGS_MATRIX[i] = embedding_vector
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model(vocab_size, embedding_dim, maxlen, embeddings_matrix):
  model = tf.keras.Sequential([
      tf.keras.layers.Embedding(vocab_size+1,
                                embedding_dim,
                                input_length=maxlen,
                                weights=[embeddings_matrix],
                                trainable=False),
      tf.keras.layers.Conv1D(32, 5, activation='relu'),
      tf.keras.layers.GlobalMaxPooling1D(),
      tf.keras.layers.Dropout(0.2),
      tf.keras.layers.Dense(64, activation='relu'),
      tf.keras.layers.Dense(1, activation='sigmoid')  ])
  model.compile(loss='binary_crossentropy',
                optimizer='adam',
                metrics=['accuracy'])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = create_model(VOCAB_SIZE, EMBEDDING_DIM, MAXLEN, EMBEDDINGS_MATRIX)
history = model.fit(train_pad_trunc_seq,
                    train_labels,
                    epochs=20,
                    validation_data=(val_pad_trunc_seq, val_labels))
<<<<<<< HEAD

# Plot training and validation loss per epoch
# Plot training and validation accuracy per epoch

=======
# Plot training and validation loss per epoch
# Plot training and validation accuracy per epoch
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Test the slope of your val_loss curve
slope, *_ = linregress(epochs, val_loss)
print(f"The slope of your validation loss curve is {slope:.5f}")

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 3 Quiz(c3): (Natural Language Processing in TensorFlow)
1) Why does sequence make a large difference when determining semantics of language?:
2. Because the order in which words appear dictate their impact on the meaning of the sentence (+)
2) How do Recurrent Neural Networks help you understand the impact of sequence on meaning?:
3. They carry meaning from one cell to the next (+)
3)How does an LSTM help understand meaning when words that qualify each other aren't necessarily beside each other in a sentence?:
4. Values from earlier words can be carried to late ones via a cell state (+)
4) What keras layer type allows LSTMs to look forward and backward in a sentence?:
4. Bidirectional (+)
5) What's the output shape of a bidirectional LSTM laery with 64 units?:
2. (None, 128) (- +)
6) When stacking LSTMs, how do you instruct an LSTM to feed the next one in the sequence?:
2. Ensure that return_sequences is set to True only on units that feed to another LSTM (+)
7) If a sentence has 120 tokens in it, and a Conv1D with 128 filters with a Kernal size of 5 is passed over it, what's the output shape?:
4. (None, 116, 128) (+)
8) What's the best way to avoid overfitting in NLP datasets?:
1. Use LSTMs
2. Use GRUs
3. Use Conv1D
4. None of the above (+)

Week4(c3): "Sequence models and literature" (Natural Language Processing in TensorFlow)

=======

Week 3 Quiz(c3): (Natural Language Processing in TensorFlow)
1) Why does sequence make a large difference when determining semantics of language?:
2. Because the order in which words appear dictate their impact on the meaning of the sentence (+)
2) How do Recurrent Neural Networks help you understand the impact of sequence on meaning?:
3. They carry meaning from one cell to the next (+)
3)How does an LSTM help understand meaning when words that qualify each other aren't necessarily beside each other in a sentence?:
4. Values from earlier words can be carried to late ones via a cell state (+)
4) What keras layer type allows LSTMs to look forward and backward in a sentence?:
4. Bidirectional (+)
5) What's the output shape of a bidirectional LSTM laery with 64 units?:
2. (None, 128) (- +)
6) When stacking LSTMs, how do you instruct an LSTM to feed the next one in the sequence?:
2. Ensure that return_sequences is set to True only on units that feed to another LSTM (+)
7) If a sentence has 120 tokens in it, and a Conv1D with 128 filters with a Kernal size of 5 is passed over it, what's the output shape?:
4. (None, 116, 128) (+)
8) What's the best way to avoid overfitting in NLP datasets?:
1. Use LSTMs
2. Use GRUs
3. Use Conv1D
4. None of the above (+)

Week4(c3): "Sequence models and literature" (Natural Language Processing in TensorFlow)

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W4L1_Generating_Text.ipynb
---------------------------------------------------------------
# Define the lyrics of the song
data= "In the town of Athy one Jeremy Lanigan \n Battered away til …"
corpus = data.lower().split("\n")
print(corpus)
[ 'in the town of athy one jeremy lanigan ', ' battered away til he .....'
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
tokenizer = Tokenizer()
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index)+1
print(f"Word index dictionary: {tokenizer.word_index}")
print(f"Total words: {total_words}")
Word index dictionary: {'and': 1, 'the': 2, 'a': 3, ...
Total words: 263
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
input_sequences = []
for line in corpus:
  token_list = tokenizer.texts_to_sequences([line])[0]
  for i in range(1, len(token_list)):
    n_gram_sequence = token_list[:i+1]
    input_sequences.append(n_gram_sequence)
max_sequence_len = max([len(x) for x in input_sequences])
# Pad all sequences
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequencee_len, padding='pre'))
# Create inputs and label by splitting the last token in the subphrases
xs, labels = input_sequences[:, :-1], input_sequences[:, -1]
# Convert the label into one-hot arrays
ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)
<<<<<<< HEAD

# Print token list and phrase
Token list: [ 0  0  0  4  2 66  8 67 68 69]
Decoded to text: ['in the town of athy one jeremy']

# Print label
One-not label: [0. 0. 0. ..... 1. ...]
Index of label: 70

=======
# Print token list and phrase
Token list: [ 0  0  0  4  2 66  8 67 68 69]
Decoded to text: ['in the town of athy one jeremy']
# Print label
One-not label: [0. 0. 0. ..... 1. ...]
Index of label: 70
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = Sequential([
    Embedding(total_words, 64, input_length=max_sequence_len-1),
    Bidirectional(LSTM(20)),
    Dense(total_words, activation='softmax')])
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
model.summary()
history = model.fit(xs, ys, epochs=500)
<<<<<<< HEAD

# Visualize the accuracy
plot_graphs(history, 'accuracy')

=======
# Visualize the accuracy
plot_graphs(history, 'accuracy')
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Define seed text
seed_text = "Laurence went to Dublin"
# Define total words to predict
next_words = 100
# Loop until desired length is reached
for _ in range(next_words):
  token_list = tokenizer.texts_to_sequences([seed_text])[0]
  token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
  probabilities = model.predict([token_list])
  predicted = np.argmax(probabilities, axis=-1)[0]
  if predicted != 0:
    output_word = tokenizer.index_word[predicted]
    seed_text += " " + output_word
print(seed_text)
Laurence went to Dublin young bacon young bacon from young bacon her myself ...

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W4L2_Generating_irish_lyrics.ipynb
---------------------------------------------------------------
# Load the dataset
data = open("./irish-lyrics-eof.txt").read()
corpus = data.lower().split("\n")
print(corpus)
['come all ye maidens young and fair', 'and you' .....
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Get sample sentence
sentence = corpus[0].split()
print(f"Sample sentence: {sentence}")
# Print the token list
print(token_list)
Sample sentence: ['come', 'all', 'ye', 'maidens', 'young', 'and', 'fair']
[51, 12, 96, 1217, 48, 2, 69]
<<<<<<< HEAD

# Pick element
elem_number = 5

=======
# Pick element
elem_number = 5
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Print token list and phrase
print(f"Token list: {xs[elem_number]}")
print(f"Decoded to text: {tokenizer.sequences_to_texts([xs[elem_number]])}\n")
# Print label
print(f"One-hot label: {ys[elem_number]}")
print(f"Index of label: {np.argmax(ys[elem_number])}")
Token list: [   0    0    0    0    0    0    0    0    0   51   12   96 1217   48    2]
Decoded to text: ['come all ye maidens young and']
One-hot label: [0. 0. 0. ... 0. 0. 0.]
Index of label: 69
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Hyperparameters
embedding_dim = 100
lstm_units = 150
learning_rate = 0.01
model = Sequential([
    Embedding(total_words, embedding_dim, input_length= max_sequence_len-1),
    Bidirectional(LSTM(lstm_units)),
    Dense(total_words, activation='softmax')])
model.compile(
    loss='categorical_crossentropy',
    optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
    metrics=['accuracy'])
model.summary()
history = model.fit(xs, ys, epochs=num_epochs)
<<<<<<< HEAD

# Visualize the accuracy
plot_graphs(history, 'accuracy')
plot_graphs(history, 'loss')

=======
# Visualize the accuracy
plot_graphs(history, 'accuracy')
plot_graphs(history, 'loss')
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Define seed text
seed_text = "help me obi-wan kinobi youre me only hope"
# Define total words to predict
next_words = 100
# Loop until desired length is reached
for _ in range(next_words):
  token_list = tokenizer.texts_to_sequences([seed_text])[0]
  token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
  probabilities = model.predict(token_list, verbose=0)
  predicted = np.argmax(probabilities, axis=-1)[0]
  if predicted != 0:
    output_word = tokenizer.index_word[predicted]
    seed_text += " " + output_word
print(seed_text)
help me obi-wan kinobi youre me only hope and girls and girls and gave ....

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W4L3_Generating_with_RNN_Shakespeare.ipynb
---------------------------------------------------------------
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
print(f"Length of text: {len(text)} characters.\n")
print(text[:250])
Length of text: 1115394 characters.
First Citizen:
Before we proceed any further, hear me speak.
All:
Speak, speak.
First Citizen:
You are all resolved rather to die than to famish?
All:
Resolved. resolved.
First Citizen:
First, you know Caius Marcius is chief enemy to the people.
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
class MyModel(tf.keras.Model):
  def __init__(self, vocab_size, embedding_dim, rnn_units):
    super().__init__(self)
    self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
    self.gru = tf.keras.layers.GRU(rnn_units,
                                   return_sequences=True,
                                   return_state=True)
    self.dense = tf.keras.layers.Dense(vocab_size)
  def call(self, inputs, states=None, return_state=False, training=False):
    x = inputs
    x = self.embedding(x, training=training)
    if states is None:
      states = self.gru.get_initial_state(x)
    x, states = self.gru(x, initial_state=states, training=training)
    x = self.dense(x, training=training)
    if return_state:
      return x, states
    else:
      return x
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
EPOCHS = 20
history = model.fit(dataset, 
                    epochs=EPOCHS, 
                    callbacks=[checkpoint_callback])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
class OneStep(tf.keras.Model):
  def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):
    super().__init__()
    self.temperature = temperature
    self.model = model
    self.chars_from_ids = chars_from_ids
    self.ids_from_chars = ids_from_chars
    skip_ids = self.ids_from_chars(['[UNK]'])[:, None]
    sparse_mask = tf.SparseTensor(
        # Put a -inf at each bad index.
        values=[-float('inf')]*len(skip_ids),
        indices=skip_ids,
        dense_shape=[len(ids_from_chars.get_vocabulary())]    )
    self.prediction_mask = tf.sparse.to_dense(sparse_mask)
  @tf.function
  def generate_one_step(self, inputs, states=None):
    input_chars = tf.strings.unicode_split(inputs, 'UTF-8')
    input_ids = self.ids_from_chars(input_chars).to_tensor()
    predicted_logits, states = self.model(inputs=input_ids,
                                          states=states,
                                          return_state=True)
    predicted_logits = predicted_logits[:, -1, :]
    predicted_logits = predicted_logits/self.temperature
    predicted_logits = predicted_logits + self.prediction_mask
    predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)
    predicted_ids = tf.squeeze(predicted_ids, axis=-1)
    predicted_chars = self.chars_from_ids(predicted_ids)
    return predicted_chars, states
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
one_step_model = OneStep(model, chars_from_ids, ids_from_chars)
print(result[0].numpy().decode('utf-8'), '\n\n' + '_'*80)
print('\nRun tim: ', end-start )
ROMEO:
Being moved!
Monday must have weals;' trembling women,
Her name by apparel for a certain text may pray.
Give me the rark, and go about that are abroad.
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
LORD ROSS:
Lay here, my lord, to call my lord, to rate;
Poor heaven, father! be not hours nor 't:
'That should short thou old my land; O, fear thou never wind-sworn
Ares to a marvellous presently at his death'. ......
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
#Advanced: Customized Training
Epoch 1 Batch 0 Loss 0.6597
Epoch 1 Batch 50 Loss 0.6368
Epoch 1 Batch 100 Loss 0.6287
Epoch 1 Batch 150 Loss 0.6278
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
Epoch 1 Loss: 0.6346
Time taken for 1 epoch 15.82 sec
....

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C3W4Lw_Predicting_next_word_Shakespeare.ipynb
---------------------------------------------------------------
SONNETS_FILE = './sonnets.txt'
with open(SONNETS_FILE) as f:
  data = f.read()
corpus = data.lower().split("\n")
print(f"There are {len(corpus)} lines of sonnets\n")
print(f"The firs 5 lines look like this:\n")
for i in  range(5):
  print(corpus[i])
There are 2159 lines of sonnets
The firs 5 lines look like this:
"from fairest creatures we desire increase,
that thereby beauty''s rose might never die,
but as the riper should by time decease,
his tender heir might bear his memory:
but thou, contracted to thine own bright eyes,"
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
tokenizer = Tokenizer()
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index) + 1
tokenizer.texts_to_sequences([corpus[0]])[0]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def features_and_labels(input_sequences, total_words):
  features = input_sequences[:, :-1]
  labels = input_sequences[:, -1]
  one_hot_labels = to_categorical(labels, num_classes=total_words)
  return features, one_hot_labels
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Split the whole corpus
features, labels = features_and_labels(input_sequences, total_words)
print(f"Features have shape: {features.shape}")
print(f"Labels have shape: {labels.shape}")
Features have shape: (15462, 10)
Labels have shape: (15462, 3211)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model(total_words, max_sequence_len):
  model = Sequential()
  model.add(Embedding(total_words, 100, input_length=max_sequence_len-1))
  model.add(Bidirectional(LSTM(128)))
  model.add(Dense(total_words, activation='softmax'))
  model.compile(loss='categorical_crossentropy',
                optimizer='adam',
                metrics=['accuracy'])
  return model
model = create_model(total_words, max_sequence_len)
history = model.fit(features, labels, epochs=50, verbose=1)
<<<<<<< HEAD

# Take a look at the training curves of your model
plt.plot(epochs, acc, 'b', label='Training accuracy')
plt.plot(epochs, loss, 'b', label='Training loss')

=======
# Take a look at the training curves of your model
plt.plot(epochs, acc, 'b', label='Training accuracy')
plt.plot(epochs, loss, 'b', label='Training loss')
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
seed_text = "Help me Obi Wan Kenobi, you're my only hope"
next_words = 100
for _ in range(next_words):
  token_list = tokenizer.texts_to_sequences([seed_text])[0]
  token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
  predicted = model.predict(token_list, verbose=0)
  predicted = np.argmax(predicted, axis=-1).item()
  output_word = tokenizer.index_word[predicted]
  seed_text += " " + output_word
print(seed_text)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
output
"Help me Obi Wan Kenobi, you're my only hope what eyes ...."

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 4 Quiz(c3): (Natural Language Processing in TensorFlow)
1) When predicting words to generate poetry, the more words predicted the more likely it will and up gibberish. Why?:
1. Because the probability that each word matches an existing phrase goes down the more words you create (+)
2) What is a major drawback of word-based training for text generation instead of character-based generation?:
2. Because there are fare more words in a typical corpus than characters, is is much more memory intensive (+)
3) What are the critical steps in preparing the input sequences for the prediction model?:
1. Pre-padding the subprhases sequences (+)
3. Generating subphrases from each line using n_gram_SEQUENCES (+)
4) In natural language processing. predicting the next item in a sequence is a classification problem. Therefore, after creating inputs and labels from the subhrases, we on-not encode the labels. What function do we use to create on-hot encoded arrays of the labels?:
3. tf.keras.utils.to_categorical (+)
5) True of False: When building the model, we use a sigmoid activated Dense output layer with one neuron per word that lights up when we predict a give word.:
2. False (+)

4) Sequences, Time Series and Prediction (13.MLg_title)

Week1(c4): "Sequences and Prediction"

=======

Week 4 Quiz(c3): (Natural Language Processing in TensorFlow)
1) When predicting words to generate poetry, the more words predicted the more likely it will and up gibberish. Why?:
1. Because the probability that each word matches an existing phrase goes down the more words you create (+)
2) What is a major drawback of word-based training for text generation instead of character-based generation?:
2. Because there are fare more words in a typical corpus than characters, is is much more memory intensive (+)
3) What are the critical steps in preparing the input sequences for the prediction model?:
1. Pre-padding the subprhases sequences (+)
3. Generating subphrases from each line using n_gram_SEQUENCES (+)
4) In natural language processing. predicting the next item in a sequence is a classification problem. Therefore, after creating inputs and labels from the subhrases, we on-not encode the labels. What function do we use to create on-hot encoded arrays of the labels?:
3. tf.keras.utils.to_categorical (+)
5) True of False: When building the model, we use a sigmoid activated Dense output layer with one neuron per word that lights up when we predict a give word.:
2. False (+)

4) Sequences, Time Series and Prediction (13.MLg_title)

Week1(c4): "Sequences and Prediction"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= series = autocorrelation_impulses(impulses_signal, {1: 0.99}) plot_series(time, series) # Here is another example where the next values are computed from those in t-1 and t-50: # Autocorrelated data can also ride a trend line and it will look like below. Non-stationary Time Series Non-stationary Time Series --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W1L1_Introduction_Time_Series.ipynb
---------------------------------------------------------------
def plot_series(time, series, format="-", start=0, end=None, label=None):
  plt.figure(figsize=(10, 6))
  plt.plot(time[start:end], series[start:end], format)
  plt.xlabel("Time")
  plt.ylabel("Value")
  if label:
    plt.legend(fontsize=14, labels=label)
  plt.grid(True)
  plt.show()
<<<<<<< HEAD

def trend(time, slope=0):
  series = slope * time
  return series

=======
def trend(time, slope=0):
  series = slope * time
  return series
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
time = np.arange(365)
slope = 0.1
series = trend(time, slope)
plot_series(time, series, label=[f'slope={slope}'])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def seasonality_pattern(season_time):
  data_pattern = np.where(season_time < 0.4,
                          np.cos(season_time*2*np.pi),
                          1/np.exp(3*season_time))
  return data_pattern
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def seasonality(time, period, amplitude=1, phase=0):
  season_time = ((time + phase) % period) / period
  data_pattern = amplitude * seasonality_pattern(season_time)
  return data_pattern
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
time = np.arange(4 * 365 + 1)
period = 365
amplitude = 40
series = seasonality(time, period=period, amplitude=amplitude)
plot_series(time, series)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
slope = 0.05
period = 365
amplitude = 40
series = trend(time, slope) + seasonality(time, period=period, amplitude=amplitude)
plot_series(time, series)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def noise(time, noise_level=1, seed=None):
  rnd = np.random.RandomState(seed)
  noise = rnd.randn(len(time)) * noise_level
  return noise
<<<<<<< HEAD

noise_level = 5
noise_signal = noise(time, noise_level=noise_level, seed=42)
plot_series(time, noise_signal)

series += noise_signal
plot_series(time, series)

=======
noise_level = 5
noise_signal = noise(time, noise_level=noise_level, seed=42)
plot_series(time, noise_signal)
series += noise_signal
plot_series(time, series)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def autocorrelation(time, amplitude, seed=None):
  rnd = np.random.RandomState(seed)
  ar = rnd.randn(len(time) + 50)
  ar[:50] = 100
  phi1 = 0.5
  phi2 = -0.1
  for step in range(50, len(time) + 50):
    ar[step] += phi1 * ar[step - 50]
    ar[step] += phi2 * ar[step - 33]
  ar = ar[50:] * amplitude
  return ar
<<<<<<< HEAD

series = autocorrelation(time, amplitude=10, seed=42)
plot_series(time[:200], series[:200])

=======
series = autocorrelation(time, amplitude=10, seed=42)
plot_series(time[:200], series[:200])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Here is a more straightforward autocorrelation function which just computes a value from the previous time step.
def autocorrelation(time, amplitude, seed=None):
  rnd = np.random.RandomState(seed)
  ar = rnd.randn(len(time) + 1)
  phi = 0.8
  for step in range(1, len(time) + 1):
    ar[step] += phi * ar[step - 1]
  ar = ar[1:] * amplitude
  return ar
<<<<<<< HEAD

series = autocorrelation(time, amplitude=10, seed=42)
plot_series(time[:200], series[:200])

=======
series = autocorrelation(time, amplitude=10, seed=42)
plot_series(time[:200], series[:200])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Another autocorrelated time series you might encounter is one where it decays predictably after random spikes. You will first define the function that generates these spikes below.
def impulses(time, num_impulses, amplitude=1, seed=None):
  rnd = np.random.RandomState(seed)
  impulse_indices = rnd.randint(len(time), size=num_impulses)
  series = np.zeros(len(time))
  for index in impulse_indices:
    series[index] += rnd.rand() * amplitude
  return series
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def autocorrelation_impulses(source, phis):
  ar = source.copy()
  for step, value in enumerate(source):
    for lag, phi in phis.items():
      if step - lag > 0:
        ar[step] += phi * ar[step - lag]
  return ar
<<<<<<< HEAD

series = autocorrelation_impulses(impulses_signal, {1: 0.99})
plot_series(time, series)

# Here is another example where the next values are computed from those in t-1 and t-50:


# Autocorrelated data can also ride a trend line and it will look like below.

Non-stationary Time Series

Non-stationary Time Series


======= series = autocorrelation_impulses(impulses_signal, {1: 0.99}) plot_series(time, series) # Here is another example where the next values are computed from those in t-1 and t-50: # Autocorrelated data can also ride a trend line and it will look like below. Non-stationary Time Series Non-stationary Time Series >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

======= series = autocorrelation_impulses(impulses_signal, {1: 0.99}) plot_series(time, series) # Here is another example where the next values are computed from those in t-1 and t-50: # Autocorrelated data can also ride a trend line and it will look like below. Non-stationary Time Series Non-stationary Time Series -->

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W1L2_Statistical_Forecasting.ipynb
---------------------------------------------------------------
# Parameters
time = np.arange(4 * 365 +1, dtype="float32")
baseline = 10
amplitude = 40
slope = 0.05
noise_level = 5
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
series += noise(time, noise_level, seed=42)
plot_series(time, series)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
plot_series(time_train, x_train)
plot_series(time_valid, x_valid)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Generate the naive forecast
naive_forecast = series[split_time -1:-1]
plot_series(time_valid, (x_valid, naive_forecast))
print(tf.keras.metrics.mean_squared_error(x_valid, naive_forecast).numpy())
print(tf.keras.metrics.mean_absolute_error(x_valid, naive_forecast).numpy())
61.827534
5.937908
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Moving Average
def moving_average_forecast(series, window_size):
  forecast = []
  for time in range(len(series) - window_size):
    forecast.append(series[time:time + window_size].mean())
  forecast = np.array(forecast)
  return forecast
moving_avg = moving_average_forecast(series, 30)[split_time - 30:]
plot_series(time_valid, (x_valid, moving_avg))
106.674576
7.142419
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Differencing
diff_series = (series[365:] - series[:-365])diff_time = time[365:]
diff_moving_avg = moving_average_forecast(diff_series, 30)
diff_moving_avg = diff_moving_avg[split_time - 365 - 30:]
diff_series = diff_series[split_time - 365:]
diff_moving_avg_plus_past = series[split_time - 365:-365] + diff_moving_avg
plot_series(time_valid, (x_valid, diff_moving_avg_plus_past))
53.764587
5.9032416
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Smoothing
diff_moving_avg_plus_smooth_past = moving_average_forecast(series[split_time - 370:-359], 11) + diff_moving_avg
plot_series(time_valid, (x_valid, diff_moving_avg_plus_smooth_past))
34.315723
4.6053295

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W1Lw_time_series.ipynb
---------------------------------------------------------------
def trend(time, slope=0):
  return slope * time
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def seasonal_pattern(season_time):
  return np.where(season_time < 0.1,
                  np.cos(season_time * 7 * np.pi),
                  1 / np.exp(5 * season_time))
<<<<<<< HEAD

def seasonality(time, period, amplitude=1, phase=0):
  season_time = ((time + phase) % period) / period
  return amplitude * seasonal_pattern(season_time)

def noise(time, noise_level=1, seed=None):
  rnd = np.random.RandomState(seed)
  return rnd.randn(len(time)) * noise_level

=======
def seasonality(time, period, amplitude=1, phase=0):
  season_time = ((time + phase) % period) / period
  return amplitude * seasonal_pattern(season_time)
def noise(time, noise_level=1, seed=None):
  rnd = np.random.RandomState(seed)
  return rnd.randn(len(time)) * noise_level
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def plot_series(time, series, format="-", title="", label=None, start=0, end=None):
  plt.plot(time[start:end], series[start:end], format, label=label)
  plt.xlabel("Time")
  plt.ylabel("Value")
  plt.title(title)
  if label:
    plt.legend()
  plt.grid(True)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
TIME = np.arange(4 * 365 + 1, dtype="float32")
y_intercept = 10
slope = 0.01
SERIES = trend(TIME, slope) + y_intercept
amplitude = 40
SERIES += seasonality(TIME, period=365, amplitude=amplitude)
noise_level = 2
SERIES += noise(TIME, noise_level, seed=42)
plt.figure(figsize=(10, 6))
plot_series(TIME, SERIES)
plt.show()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def compute_metrics(true_series, forecast):
  mse = tf.keras.metrics.mean_squared_error(true_series, forecast).numpy()
  mae = tf.keras.metrics.mean_absolute_error(true_series, forecast).numpy()
  return mse, mae
<<<<<<< HEAD

naive_forecast = SERIES[SPLIT_TIME - 1:-1]
mse: 19.58, mae: 2.60 for naive forecast

=======
naive_forecast = SERIES[SPLIT_TIME - 1:-1]
mse: 19.58, mae: 2.60 for naive forecast
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def moving_average_forecast(series, window_size):
  forecast = []
  for time  in range(len(series) - window_size):
    forecast.append(series[time:time + window_size].mean())
  np_forecast = np.array(forecast)
  return np_forecast
<<<<<<< HEAD

moving_avg = moving_average_forecast(SERIES, window_size=30)
moving_avg = moving_avg[1100 - 30:]
mse: 65.79, mae: 4.30 for moving average forecast

diff_series = (SERIES[365:] - SERIES[:-365])
diff_time = TIME[365:]

=======
moving_avg = moving_average_forecast(SERIES, window_size=30)
moving_avg = moving_avg[1100 - 30:]
mse: 65.79, mae: 4.30 for moving average forecast
diff_series = (SERIES[365:] - SERIES[:-365])
diff_time = TIME[365:]
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
diff_moving_avg = moving_average_forecast(diff_series, 50)
diff_moving_avg = diff_moving_avg[SPLIT_TIME - 365 - 50:]
past_series = SERIES[SPLIT_TIME - 365:-365]
diff_moving_avg_plus_past = past_series + diff_moving_avg
mse: 8.50, mae: 2.33 for moving average plus past forecast
<<<<<<< HEAD


======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

Week 1 Quiz(c4): (Sequences, Time Series and Prediction)
1) What is an example of a Univariate time series?:
3. Hour by hour temperature (+)
2) What is an example of a Multivariate time series?:
1. Hour by hour weather (+)
3) What is imputed data?:
2. A projection of unknown (usually past or missing) data (+)
4) A sound wave is a good example of time series data:
2. True (+)
5) What is a Seasonality?:
4. A regular change in shape of the data (+)
6) What is trend?:
3. An overall direction for data regardless of direction (+)
7) In the context of time series, what is noise?:
3. Unpredictable changes in time series data (+)
8) What is autocorrelation?:
4. Data that follows a predictable shape, even if the scale is different (+)
9)What is a non-stationary time series?:
1. One that has a disruptive event breaking trend and seasonality (+)

Week2(c4): "Deep Neural Networks for Time Series"

======= -->

Week 1 Quiz(c4): (Sequences, Time Series and Prediction)
1) What is an example of a Univariate time series?:
3. Hour by hour temperature (+)
2) What is an example of a Multivariate time series?:
1. Hour by hour weather (+)
3) What is imputed data?:
2. A projection of unknown (usually past or missing) data (+)
4) A sound wave is a good example of time series data:
2. True (+)
5) What is a Seasonality?:
4. A regular change in shape of the data (+)
6) What is trend?:
3. An overall direction for data regardless of direction (+)
7) In the context of time series, what is noise?:
3. Unpredictable changes in time series data (+)
8) What is autocorrelation?:
4. Data that follows a predictable shape, even if the scale is different (+)
9)What is a non-stationary time series?:
1. One that has a disruptive event breaking trend and seasonality (+)

Week2(c4): "Deep Neural Networks for Time Series"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W2L1_ Preparing_Time_Series.ipynb
---------------------------------------------------------------
# Flatten the Windows
# Generate a tf dataset with 10 elements (i.e. numbers 0 to 9)
dataset = tf.data.Dataset.range(10)
# Window the data but only take those with the specified size
dataset = dataset.window(5, shift=1, drop_remainder=True)
# Flatten the windows by putting its elements in a single batch
dataset = dataset.flat_map(lambda window: window.batch(5))
# Print the results
for window in dataset:
  print(window.numpy())
[0 1 2 3 4]
[1 2 3 4 5]
[2 3 4 5 6]
[3 4 5 6 7]
[4 5 6 7 8]
[5 6 7 8 9]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Group into features and labels
# Generate a tf dataset with 10 elements (i.e. numbers 0 to 9)
dataset = tf.data.Dataset.range(10)
# Window the data but only take those with the specified size
dataset = dataset.window(5, shift=1, drop_remainder=True)
# Flatten the windows by putting its elements in a single batch
dataset = dataset.flat_map(lambda window: window.batch(5))
# Create tuples with features (first four elements of the window) and labels (last element)
dataset = dataset.map(lambda window: (window[:-1], window[-1]))
# Print the results
for x, y in dataset:
  print(x.numpy(), y.numpy())
[0 1 2 3] 4
[1 2 3 4] 5
[2 3 4 5] 6
[3 4 5 6] 7
[4 5 6 7] 8
[5 6 7 8] 9
<<<<<<< HEAD

# Shuffle the data
# Shuffle the windows
dataset = dataset.shuffle(buffer_size=10)

=======
# Shuffle the data
# Shuffle the windows
dataset = dataset.shuffle(buffer_size=10)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Create batches for training
# Create batches of windows
dataset = dataset.batch(2).prefetch(1)
output
[[1 2 3 4]
 [0 1 2 3]] [5 4]
[[5 6 7 8]
 [4 5 6 7]] [9 8]
[[3 4 5 6]
 [2 3 4 5]] [7 6]

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W2L2_ Single_Layer_NN_Time_Series.ipynb
---------------------------------------------------------------
# Generate the Synthetic Data
# Parameters
time = np.arange(4 * 365 + 1, dtype="float32")
baseline = 10
amplitude = 40
slope = 0.05
noise_level = 5
# Create the series
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
# Update with noise
series += noise(time, noise_level, seed=42)
# Plot the results
plot_series(time, series)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Define the split time
split_time = 1000
# Get the train set
time_train = time[:split_time]
x_train = series[:split_time]
# Get the validation set
time_valid = time[split_time:]
x_valid = series[split_time:]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Prepare features and labels
def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
  # Generate a TF Dataset from the series values
  dataset = tf.data.Dataset.from_tensor_slices(series)
  # Window the data but only take those with the specified size
  dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
  # Flatten the windows by putting its elements in a single batch
  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
  # Create tuples with features and labels
  dataset = dataset.map(lambda window: (window[:-1], window[-1]))
  # Shuffle the windows
  dataset = dataset.shuffle(shuffle_buffer)
  # Create batches of windows
  dataset = dataset.batch(batch_size).prefetch(1)
  return dataset
<<<<<<< HEAD

# Generate the dataset windows
dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)

=======
# Generate the dataset windows
dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Build the single layer neural network
l0 = tf.keras.layers.Dense(1, input_shape=[window_size])
model = tf.keras.models.Sequential([l0])
# Set the training parameters
model.compile(loss="mse",
              optimizer=tf.keras.optimizers.SGD(learning_rate=1e-6, momentum=0.9))
# Train the model
model.fit(dataset, epochs=100)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Model Prediction
# Initialize a list
forecast = []
# Use the model to predict data points per window size
for time in range(len(series) - window_size):
  forecast.append(model.predict(series[time:time + window_size][np.newaxis]))
# Slice the points that are aligned with the validation set
forecast = forecast[split_time - window_size:]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Compute the metrics
46.76
5.1

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W2L3_DNN_with_Time_Series_Data.ipynb
---------------------------------------------------------------
# Generate the Synthetic Data
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
series += noise(time, noise_level, seed=42)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
  dataset = tf.data.Dataset.from_tensor_slices(series)
  dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
  dataset = dataset.map(lambda window: (window[:-1], window[-1]))
  dataset = dataset.shuffle(shuffle_buffer)
  dataset = dataset.batch(batch_size).prefetch(1)
  return dataset
dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model_baseline = tf.keras.models.Sequential([
    tf.keras.layers.Dense(10, input_shape=[window_size], activation="relu"),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(1)])
model_baseline.summary()
model_baseline.compile(loss='mse',
                       optimizer=tf.keras.optimizers.SGD(learning_rate=1e-6, momentum=0.9))
model_baseline.fit(dataset, epochs=100)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
forecast =[]
forecast_series = series[split_time - window_size:]
for time in range(len(forecast_series) - window_size):
  forecast.append(model_baseline.predict(forecast_series[time:time + window_size][np.newaxis]))
results = np.array(forecast).squeeze()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Compute the metrics
print(tf.keras.metrics.mean_squared_error(x_valid, results).numpy())
print(tf.keras.metrics.mean_absolute_error(x_valid, results).numpy())
45.5331
4.9760103
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Tune the learning rate
model_tune = tf.keras.models.Sequential([
    tf.keras.layers.Dense(10, input_shape=[window_size], activation='relu'),
    tf.keras.layers.Dense(10, activation="relu"),
    tf.keras.layers.Dense(1)])
<<<<<<< HEAD

# Set the learning rate scheduler
lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: 1e-8 * 10**(epoch / 20))

optimizer = tf.keras.optimizers.SGD(momentum=0.9)
model_tune.compile(loss='mse', optimizer=optimizer)
history = model_tune.fit(dataset, epochs=100, callbacks=[lr_schedule])

#Next step is to plot the results of the training. 

=======
# Set the learning rate scheduler
lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: 1e-8 * 10**(epoch / 20))
optimizer = tf.keras.optimizers.SGD(momentum=0.9)
model_tune.compile(loss='mse', optimizer=optimizer)
history = model_tune.fit(dataset, epochs=100, callbacks=[lr_schedule])
#Next step is to plot the results of the training. 
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model_tune = tf.keras.models.Sequential([
    tf.keras.layers.Dense(10, activation='relu', input_shape=[window_size]),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(1)])
optimizer = tf.keras.optimizers.SGD(learning_rate=1e-5, momentum=0.9)
model_tune.compile(loss='mse', optimizer=optimizer)
history = model_tune.fit(dataset, epochs=200)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Plot the loss
# You can get the preictions again and overlay it on the validation set.
# Compute the metrics
42.18
4.81

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W2Lw_NN_Predicting_time_series.ipynb
---------------------------------------------------------------
def generate_time_series():
  time = np.arange(4 * 365 + 1, dtype="float32")
  y_intercept = 10
  slope = 0.005
  series = trend(time, slope) + y_intercept
  amplitude = 50
  series += seasonality(time, period=365, amplitude=amplitude)
  noise_level = 3
  series += noise(time, noise_level, seed=51)
  return time, series
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Save all "global" variables within the G class (G stands for global)
@dataclass
class G:
  TIME, SERIES = generate_time_series()
  SPLIT_TIME = 1100
  WINDOW_SIZE = 20
  BATCH_SIZE = 32
  SHUFFLE_BUFFER_SIZE = 1000
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def train_val_split(time, series, time_step=G.SPLIT_TIME):
  time_train = time[:time_step]
  series_train = series[:time_step]
  time_valid = time[time_step:]
  series_valid = series[time_step:]
  return time_train, series_train, time_valid, series_valid
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def windowed_dataset(series, window_size=G.WINDOW_SIZE, batch_size=G.BATCH_SIZE, shuffle_buffer=G.SHUFFLE_BUFFER_SIZE):
  dataset = tf.data.Dataset.from_tensor_slices(series)
  dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
  dataset = dataset.shuffle(shuffle_buffer)
  dataset = dataset.map(lambda window: (window[:-1], window[-1]))
  dataset = dataset.batch(batch_size).prefetch(1)
  return dataset
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model(window_size=G.WINDOW_SIZE):
  model = tf.keras.models.Sequential([
      tf.keras.layers.Dense(20, input_shape=[window_size], activation="relu"),
      tf.keras.layers.Dense(20, activation='relu'),
      tf.keras.layers.Dense(30, activation='relu'),
      tf.keras.layers.Dense(1)  ])
  model.compile(loss="mse",
                optimizer=tf.keras.optimizers.SGD(learning_rate=1e-6, momentum=0.9))
  return model
<<<<<<< HEAD

dataset = windowed_dataset(series_train)
model = create_model()
model.fit(dataset, epochs=100)

=======
dataset = windowed_dataset(series_train)
model = create_model()
model.fit(dataset, epochs=100)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def compute_metrics(true_series, forecast):
  mse = tf.keras.metrics.mean_squared_error(true_series, forecast).numpy()
  mae = tf.keras.metrics.mean_absolute_error(true_series, forecast).numpy()
  return mse, mae
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def generate_forecast(series=G.SERIES, split_time=G.SPLIT_TIME, window_size=G.WINDOW_SIZE):
  forecast = []
  for time in range(len(series) - window_size):
    forecast.append(model.predict(series[time:time + window_size][np.newaxis]))
  forecast = forecast[split_time - window_size:]
  results = np.array(forecast)[:, 0, 0]
  return results
<<<<<<< HEAD

# Save the forecast
dnn_forecast = generate_forecast()

mse: 29.33, mae: 3.33 for forecast

======= # Save the forecast dnn_forecast = generate_forecast() mse: 29.33, mae: 3.33 for forecast >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

Week 2 Quiz(c4): (Sequences, Time Series and Prediction)
1) What is a windowed dataset?:
1. A fixed-size subset of a time series (+)
2) What does 'drop_remainder=True' do?:
2. It ensures that all rows in the data window are the same length by cropping data (+)
3) What's the correct line of code to split an n column window into n-1 columns for features and 1 column for a label?:
2. dataset=dataset.map(lambda window:(window[:-1], window[-1:])) (+)
4) What does MSE stand for?:
3. Mean Squared error (+)
5) What does MAE stand for?:
3. Mean Absolute error (+)
6) If time values are in time[], series values are in series[] and we want to split the series into training and validation at time split_time, what is the correct code?:
4.: time_train = time[:split_time] (+)
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
7) If you want to inspect the learned parameters in a layer after training, what's a good technique to use?:
1. Assign a variable to the layer and add it to the model using that variable, Inspect its properties after training. (+)
8) How do you set the learning rate of the SGD optimizer?:
3. Use the learning_rate property (+)
9) If you want to amend the learning rate of the optimizer on the fly, after each epoch. What do you do?:
3. Use a LearningRateScheduler object in the callbacks namespace and assign that to the callback (+)

Week3(c4): "Recurrent Neural Networks for Time Series"

=======

Week 2 Quiz(c4): (Sequences, Time Series and Prediction)
1) What is a windowed dataset?:
1. A fixed-size subset of a time series (+)
2) What does 'drop_remainder=True' do?:
2. It ensures that all rows in the data window are the same length by cropping data (+)
3) What's the correct line of code to split an n column window into n-1 columns for features and 1 column for a label?:
2. dataset=dataset.map(lambda window:(window[:-1], window[-1:])) (+)
4) What does MSE stand for?:
3. Mean Squared error (+)
5) What does MAE stand for?:
3. Mean Absolute error (+)
6) If time values are in time[], series values are in series[] and we want to split the series into training and validation at time split_time, what is the correct code?:
4.: time_train = time[:split_time] (+)
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
7) If you want to inspect the learned parameters in a layer after training, what's a good technique to use?:
1. Assign a variable to the layer and add it to the model using that variable, Inspect its properties after training. (+)
8) How do you set the learning rate of the SGD optimizer?:
3. Use the learning_rate property (+)
9) If you want to amend the learning rate of the optimizer on the fly, after each epoch. What do you do?:
3. Use a LearningRateScheduler object in the callbacks namespace and assign that to the callback (+)

Week3(c4): "Recurrent Neural Networks for Time Series"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W3L1_Simple_RNN.ipynb
---------------------------------------------------------------
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
series += noise(time, noise_level, seed=42)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
  dataset = tf.data.Dataset.from_tensor_slices(series)
  dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
  dataset = dataset.map(lambda window: (window[:-1], window[-1]))
  dataset = dataset.shuffle(shuffle_buffer)
  dataset = dataset.batch(batch_size).prefetch(1)
  return dataset
<<<<<<< HEAD

# Generate the dataset windows
dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)

=======
# Generate the dataset windows
dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model_tune = tf.keras.models.Sequential([
    tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
                           input_shape=[window_size]),
    tf.keras.layers.SimpleRNN(40, return_sequences=True),
    tf.keras.layers.SimpleRNN(40),
    tf.keras.layers.Dense(1),
    tf.keras.layers.Lambda(lambda x: x * 100)])
model_tune.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: 1e-8 * 10 ** (epoch / 20))
optimizer = tf.keras.optimizers.SGD(momentum=0.9)
model_tune.compile(loss=tf.keras.losses.Huber(), optimizer=optimizer)
history = model_tune.fit(dataset, epochs=100, callbacks=[lr_schedule])
<<<<<<< HEAD

# You can visualize the results and pick an optimal learning rate.

=======
# You can visualize the results and pick an optimal learning rate.
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = tf.keras.models.Sequential([
    tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
                          input_shape=[window_size]),
    tf.keras.layers.SimpleRNN(40, return_sequences=True),
    tf.keras.layers.SimpleRNN(40),
    tf.keras.layers.Dense(1),
    tf.keras.layers.Lambda(lambda x: x * 100.0)])
learning_rate = 8e-7
optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
              optimizer=optimizer,
              metrics=['mae'])
history = model.fit(dataset, epochs=100)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
forecast = []
forecast_series = series[split_time - window_size:]
for time in range(len(forecast_series) - window_size):
  forecast.append(model.predict(forecast_series[time:time + window_size][np.newaxis]))
results = np.array(forecast).squeeze()
plot_series(time_valid, (x_valid, results))
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def model_forecast(model, series, window_size, batch_size):
  dataset = tf.data.Dataset.from_tensor_slices(series)
  dataset = dataset.window(window_size, shift=1, drop_remainder=True)
  dataset = dataset.flat_map(lambda w: w.batch(window_size))
  dataset = dataset.batch(batch_size).prefetch(1)
  forecast = model.predict(dataset)
  return forecast
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
forecast_series = series[split_time - window_size:-1]
forecast = model_forecast(model, forecast_series, window_size, batch_size)
results = forecast.squeeze()
plot_series(time_valid, (x_valid, results))
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Compute the MSE and MAE
print(tf.keras.metrics.mean_squared_error(x_valid, results).numpy())
print(tf.keras.metrics.mean_absolute_error(x_valid, results).numpy())
65.11
6.25

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W3L2_LSTM_for_forecasting.ipynb
---------------------------------------------------------------
# Generate the dataset windows
dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model_tune = tf.keras.models.Sequential([
    tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
                           input_shape=[window_size]),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(1),
    tf.keras.layers.Lambda(lambda x: x * 100.0)])
model_tune.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Set the learning rate scheduler
lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: 1e-8 * 10 ** (epoch / 20))
optimizer = tf.keras.optimizers.SGD(momentum=0.9)
model_tune.compile(loss=tf.keras.losses.Huber(), optimizer=optimizer)
history = model_tune.fit(dataset, epochs=100, callbacks=[lr_schedule])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Define the learning rate array
lrs = 1e-8 * (10 ** (np.arange(100) / 20))
plt.figure(figsize=(10, 6))
plt.grid(True)
plt.semilogx(lrs, history.history["loss"])
plt.tick_params("both", length=10, width=1, which="both")
plt.axis([1e-8, 1e-3, 0, 30])
<<<<<<< HEAD

# Reset states generated by Keras
tf.keras.backend.clear_session()

=======
# Reset states generated by Keras
tf.keras.backend.clear_session()
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = tf.keras.models.Sequential([
    tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
                           input_shape=[None]),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(1),
    tf.keras.layers.Lambda(lambda x: x * 100.0)])
learning_rate = 1e-5
optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
              optimizer=optimizer,
              metrics=["mae"])
history = model.fit(dataset, epochs=100)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def model_forecast(model, series, window_size, batch_size):
  dataset = tf.data.Dataset.from_tensor_slices(series)
  dataset = dataset.window(window_size, shift=1, drop_remainder=True)
  dataset = dataset.flat_map(lambda w: w.batch(window_size))
  dataset = dataset.batch(batch_size).prefetch(1)
  forecast = model.predict(dataset)
  return forecast
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Reduce the original series
forecast_series = series[split_time-window_size:-1]
forecast = model_forecast(model, forecast_series, window_size, batch_size)
# Drop single dimensional axis
results = forecast.squeeze()
plot_series(time_valid, (x_valid, results))
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Compute the MSE and MAE
print(tf.keras.metrics.mean_squared_error(x_valid, results).numpy())
print(tf.keras.metrics.mean_absolute_error(x_valid, results).numpy())
58.02
5.48

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= mse, mae = compute_metrics(series_valid, rnn_forecast) mse: 28.74, mae: 3.21 for forecast --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W3Lw_RNNs_predict_time_series.ipynb
---------------------------------------------------------------
def generate_time_series():
  time = np.arange(4 * 365 + 1, dtype="float32")
  y_intercept = 10
  slope = 0.005
  series = trend(time, slope) + y_intercept
  amplitude = 50
  series += seasonality(time, period=365, amplitude=amplitude)
  noise_level = 3
  series += noise(time, noise_level, seed=51)
  return time, series
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
@dataclass
class G:
  TIME, SERIES = generate_time_series()
  SPLIT_TIME = 1100
  WINDOW_SIZE = 20
  BATCH_SIZE = 32
  SHUFFLE_BUFFER_SIZE = 1000
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def windowed_dataset(series, window_size=G.WINDOW_SIZE, batch_size=G.BATCH_SIZE, shuffle_buffer=G.SHUFFLE_BUFFER_SIZE):
  dataset = tf.data.Dataset.from_tensor_slices(series)
  dataset = dataset.window(window_size +1, shift=1, drop_remainder=True)
  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
  dataset = dataset.shuffle(shuffle_buffer)
  dataset = dataset.map(lambda window: (window[:-1], window[-1]))
  dataset = dataset.batch(batch_size).prefetch(1)
  return dataset
dataset = windowed_dataset(series_train)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_uncompiled_model():
  model = tf.keras.models.Sequential([
      tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
                             input_shape=[None]),
      tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),
      tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
      tf.keras.layers.Dense(1),
      tf.keras.layers.Lambda(lambda x: x * 100.0)  ])
  return model
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def adjust_learning_rate():
  model = create_uncompiled_model()
  lr_schedule = tf.keras.callbacks.LearningRateScheduler(lambda epoch: 1e-6 * 10**(epoch / 20))
  optimizer = tf.keras.optimizers.SGD(momentum=0.9)
  model.compile(loss=tf.keras.losses.Huber(),
                optimizer=optimizer,
                metrics=["mae"])
  history = model.fit(dataset, epochs=100, callbacks=[lr_schedule])
  return history
lr_history = adjust_learning_rate()
<<<<<<< HEAD

plt.semilogx(lr_history.history["lr"], lr_history.history["loss"])
plt.axis([1e-6, 1, 0, 30 ])

=======
plt.semilogx(lr_history.history["lr"], lr_history.history["loss"])
plt.axis([1e-6, 1, 0, 30 ])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def create_model():
  tf.random.set_seed(51)
  model = create_uncompiled_model()
  learning_rate = 1e-5
  optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
  model.compile(loss=tf.keras.losses.Huber(),
                optimizer=optimizer,
                metrics=["mae"])
  return model
<<<<<<< HEAD

model = create_model()
history = model.fit(dataset, epochs=50)

=======
model = create_model()
history = model.fit(dataset, epochs=50)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def compute_metrics(true_series, forecast):
  mse = tf.keras.metrics.mean_squared_error(true_series, forecast).numpy()
  mae = tf.keras.metrics.mean_absolute_error(true_series, forecast).numpy()
  return mse, mae
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def model_forecast(model, series, window_size):
  ds = tf.data.Dataset.from_tensor_slices(series)
  ds = ds.window(window_size, shift=1, drop_remainder=True)
  ds = ds.flat_map(lambda w: w.batch(window_size))
  ds = ds.batch(32).prefetch(1)
  forecast = model.predict(ds)
  return forecast
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Compute the forecast for all the series
rnn_forecast = model_forecast(model, G.SERIES, G.WINDOW_SIZE).squeeze()
# Slize the forecast to get only the predictions for the validation set
rnn_forecast = rnn_forecast[G.SPLIT_TIME - G.WINDOW_SIZE:-1]
<<<<<<< HEAD

mse, mae = compute_metrics(series_valid, rnn_forecast)
mse: 28.74, mae: 3.21 for forecast


======= mse, mae = compute_metrics(series_valid, rnn_forecast) mse: 28.74, mae: 3.21 for forecast >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

Week 3 Quiz(c4): (Sequences, Time Series and Prediction)
1) If X is the standard notation for the input to an RNN, what are the standard notations for the outputs?:
3. Y(hat) and H (+)
2) What is a sequence to vector if an RNN has 30 cells numbered 0 to 29:
2. The Y(hat) for the last cell (+)
3) What does a Lambda layers in a neural network do?:
2. Allows you to execute arbitrary code while training (+)
4) What does the axis parameter of tf.expand_dims do? :
1. Defines the dimension index at which you will expand the shape of the tensor (+)
5) A new loss function was introduced in this module, name after a famous statistician. What is it called?:
2. Huber loss (+)
6) What's the primary difference between a simple RNN and an LSTM?:
1. In addition to the H output, LSTMs have a cell state that runs across all cells (+)
7) If you want to clear out all temporary variables that tensorflow might have from previous sessions, what code do you run?:
4. tf.keras.backend.clear_session() (+)
8) What happens if you define a neural network with these two layers?:
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Dense(1):
3. Your model will fail because you need return_sequences=True after the first LSTM layer (+)

Week4(c4): "Real-world time series data"

======= mse, mae = compute_metrics(series_valid, rnn_forecast) mse: 28.74, mae: 3.21 for forecast -->

Week 3 Quiz(c4): (Sequences, Time Series and Prediction)
1) If X is the standard notation for the input to an RNN, what are the standard notations for the outputs?:
3. Y(hat) and H (+)
2) What is a sequence to vector if an RNN has 30 cells numbered 0 to 29:
2. The Y(hat) for the last cell (+)
3) What does a Lambda layers in a neural network do?:
2. Allows you to execute arbitrary code while training (+)
4) What does the axis parameter of tf.expand_dims do? :
1. Defines the dimension index at which you will expand the shape of the tensor (+)
5) A new loss function was introduced in this module, name after a famous statistician. What is it called?:
2. Huber loss (+)
6) What's the primary difference between a simple RNN and an LSTM?:
1. In addition to the H output, LSTMs have a cell state that runs across all cells (+)
7) If you want to clear out all temporary variables that tensorflow might have from previous sessions, what code do you run?:
4. tf.keras.backend.clear_session() (+)
8) What happens if you define a neural network with these two layers?:
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Dense(1):
3. Your model will fail because you need return_sequences=True after the first LSTM layer (+)

Week4(c4): "Real-world time series data"

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 ======= --> >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W4L1_Convolutions_with_LSTMs.ipynb
---------------------------------------------------------------
# Create the series
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
# Update with noise
series += noise(time, noise_level, seed=42)
# Plot the results
plot_series(time, series, xlabel="Time", ylabel="Value")
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Define the split time
split_time = 1000
# Get the train set
time_train = time[:split_time]
x_train = series[:split_time]
# Get the validation set
time_valid = time[split_time:]
x_valid = series[split_time:]
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Parameters
window_size = 20
batch_size = 16
shuffle_buffer_size = 1000
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
  # Generate a TF Dataset from the series values
  dataset = tf.data.Dataset.from_tensor_slices(series)
  # Window the data but only take those with the specified size
  dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
  # Flatten the windows my putting its elements in a single batch
  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
  # Create tuples with features and labels
  dataset = dataset.map(lambda window: (window[:-1], window[-1]))
  # Shuffle the windows
  dataset = dataset.shuffle(shuffle_buffer)
  # Create batches of windows
  dataset = dataset.batch(batch_size). prefetch(1)
  return dataset
<<<<<<< HEAD

train_set = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)

=======
train_set = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv1D(filters=64, kernel_size=3,
                           strides=1, padding="causal",
                           activation="relu",
                           input_shape=[window_size, 1]),
    tf.keras.layers.LSTM(64, return_sequences=True),
    tf.keras.layers.LSTM(64),
    tf.keras.layers.Dense(1),
    tf.keras.layers.Lambda(lambda x: x * 400)])
model.summary()
<<<<<<< HEAD

init_weights = model.get_weights()

=======
init_weights = model.get_weights()
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: 1e-8 * 10**(epoch / 20))
optimizer = tf.keras.optimizers.SGD(momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(), optimizer=optimizer)
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Reset states generated by Keras
tf.keras.backend.clear_session()
# Reset the weights
model.set_weights(init_weights)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
learning_rate = 5e-7
optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
              optimizer=optimizer,
              metrics=["mae"])
history = model.fit(train_set, epochs=500)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
mae = history.history['mae']
loss = history.history['loss']
epochs = range(len(loss))
plot_series(
    x=epochs,
    y=(mae, loss),
    title="MAE and Loss",
    xlabel="Epochs",
    legend=["MAE", "Loss"] )
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
def model_forecast(model, series, window_size, batch_size):
  dataset = tf.data.Dataset.from_tensor_slices(series)
  dataset = dataset.window(window_size, shift=1, drop_remainder=True)
  dataset = dataset.flat_map(lambda w: w.batch(window_size))
  dataset = dataset.batch(batch_size).prefetch(1)
  forecast = model.predict(dataset)
  return forecast
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
forecast_series = series[split_time-window_size:-1]
forecast = model_forecast(model, forecast_series, window_size, batch_size)
results = forecast.squeeze()
plot_series(time_valid, (x_valid, results))
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
print(tf.keras.metrics.mean_squared_error(x_valid, results).numpy())
print(tf.keras.metrics.mean_absolute_error(x_valid, results).numpy())
45.73067
4.9953823
<<<<<<< HEAD


======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

======= -->

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W4L2_Sunspots_DNN_only.ipynb
---------------------------------------------------------------
!head Sunspots.csv
,Date,Monthly Mean Total Sunspot Number
0,1749-01-31,96.7
1,1749-02-28,104.3 …
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
split_time = 3000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
<<<<<<< HEAD
 
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
window_size = 30
batch_size = 32
shuffle_buffer_size = 1000
train_set = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(30, input_shape=[window_size], activation='relu'),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(1)])
model.summary()
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: 1e-8 * 10**(epoch / 20))
optimizer = tf.keras.optimizers.SGD(momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(), optimizer=optimizer)
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
tf.keras.backend.clear_session()
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(30, input_shape=[window_size], activation='relu'),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(1) ])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
learning_rate = 1e-5
optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
              optimizer=optimizer,
              metrics=["mae"])
history = model.fit(train_set, epochs=100)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
forecast_series = series[split_time - window_size :-1]
forecast = model_forecast(model, forecast_series, window_size, batch_size)
results = forecast.squeeze()
plot_series(time_valid , (x_valid, results))
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
print(tf.keras.metrics.mean_absolute_error(x_valid, results).numpy())
14.480816

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W4L3_Sunspots_CNN_RNN_DNN.ipynb
---------------------------------------------------------------
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv1D(filters=64,
                           kernel_size=3,
                           strides=1,
                           activation='relu',
                           padding="causal",
                           input_shape=[window_size, 1]),
    tf.keras.layers.LSTM(64, return_sequences=True),
    tf.keras.layers.LSTM(64),
    tf.keras.layers.Dense(30, activation="relu"),
    tf.keras.layers.Dense(10, activation="relu"),
    tf.keras.layers.Dense(1),
    tf.keras.layers.Lambda(lambda x: x * 400)])
model.summary()
<<<<<<< HEAD

# Train the model
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])

=======
# Train the model
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
# Reset states generated by Keras
tf.keras.backend.clear_session()
# Reset the weights
model.set_weights(init_weights)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
learning_rate = 3e-7
optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
              optimizer=optimizer,
              metrics=["mae"])
history = model.fit(train_set, epochs=100)
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
mae = history.history['mae']
loss = history.history['loss']
epochs = range(len(loss))
plot_series(
    x=epochs,
    y=(mae, loss),
    title="MAE and Loss",
    xlabel="MAE",
    ylabel='Loss',
    legend=["MAE", "Loss"])
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
forecast_series = series[split_time - window_size :-1]
forecast = model_forecast(model, forecast_series, window_size, batch_size)
results = forecast.squeeze()
plot_series(time_valid, (x_valid, results))
<<<<<<< HEAD

=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
print(tf.keras.metrics.mean_absolute_error(x_valid, results).numpy())
14.986037

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

=======

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1

C4W4_Assignment_min_temp_Melbourne.ipynb
---------------------------------------------------------------
@dataclass
class G:
    TEMPERATURES_CSV = './data/daily-min-temperatures.csv'
    times, temperatures = parse_data_from_file(TEMPERATURES_CSV)
    TIME = np.array(times)
    SERIES = np.array(temperatures)
    SPLIT_TIME = 2500
    WINDOW_SIZE = 64
    BATCH_SIZE = 32
    SHUFFLE_BUFFER_SIZE = 1000
def windowed_dataset(series, window_size=G.WINDOW_SIZE, batch_size=G.BATCH_SIZE, shuffle_buffer=G.SHUFFLE_BUFFER_SIZE):
    ds = tf.data.Dataset.from_tensor_slices(series)
    ds = ds.window(window_size + 1, shift=1, drop_remainder=True)
    ds = ds.flat_map(lambda w: w.batch(window_size + 1))
    ds = ds.shuffle(shuffle_buffer)
    ds = ds.map(lambda w: (w[:-1], w[-1]))
    ds = ds.batch(batch_size).prefetch(1)
    return ds
train_set = windowed_dataset(series_train, window_size=G.WINDOW_SIZE, batch_size=G.BATCH_SIZE, shuffle_buffer=G.SHUFFLE_BUFFER_SIZE)
def create_uncompiled_model():
    model = tf.keras.models.Sequential([
        tf.keras.layers.Conv1D(filters=64,
                               kernel_size=3,
                              strides=1,
                              activation="relu",
                              padding="causal",
                              input_shape=[G.WINDOW_SIZE, 1]),
        tf.keras.layers.LSTM(64, return_sequences=True),
        tf.keras.layers.LSTM(64),
        tf.keras.layers.Dense(30, activation="relu"),
        tf.keras.layers.Dense(10, activation="relu"),
        tf.keras.layers.Dense(5, activation="relu"),
        tf.keras.layers.Dense(1)    ])
    return model
def adjust_learning_rate(dataset):
    model = create_uncompiled_model()
    lr_schedule = tf.keras.callbacks.LearningRateScheduler(lambda epoch: 1e-4 * 10**(epoch / 20))
    optimizer = tf.keras.optimizers.SGD(momentum=0.9)
    model.compile(loss=tf.keras.losses.Huber(),
                  optimizer=optimizer,
                  metrics=["mae"])
    history = model.fit(dataset, epochs=100, callbacks=[lr_schedule])
    return history
lr_history = adjust_learning_rate(train_set)
def create_model():
    model = create_uncompiled_model()
    learning_rate = 1e-3
    optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
    model.compile(loss=tf.keras.losses.Huber(),
                  optimizer=optimizer,
                  metrics=["mae"])
    return model
model = create_model()
history = model.fit(train_set, epochs=50)
def compute_metrics(true_series, forecast):
    mse = tf.keras.metrics.mean_squared_error(true_series, forecast).numpy()
    mae = tf.keras.metrics.mean_absolute_error(true_series, forecast).numpy()
    return mse, mae
def model_forecast(model, series, window_size):
    ds = tf.data.Dataset.from_tensor_slices(series)
    ds = ds.window(window_size, shift=1, drop_remainder=True)
    ds = ds.flat_map(lambda w: w.batch(window_size))
    ds = ds.batch(32).prefetch(1)
    forecast = model.predict(ds)
    return forecast
# Compute the forecast for all the series
rnn_forecast = model_forecast(model, G.SERIES, G.WINDOW_SIZE).squeeze()
# Slice the forecast to get only the predictions for the validation set
rnn_forecast = rnn_forecast[G.SPLIT_TIME - G.WINDOW_SIZE:-1]
mse, mae = compute_metrics(series_valid, rnn_forecast)
print(f"mse: {mse:.2f}, mae: {mae:.2f} for forecast")
mse: 5.66, mae: 1.86 

<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

For resume, profession ML (13.MLg_title)

Profession:
ML Software Engineer; Data Scientist; Automation Engineers; NLP Engineers; AI Experts; Research Scientions; Pre-sales ML Solution Engineer

Keywords deeplearning AI:
" Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning":
1. A new Programming Paradigm:
frameworks TensorFlow, python library: scikit-learn, pandas, matplotlib, seaborn
2. Introduction to Computer Vision:
python library: numpy, matplotlib.pyplot, tf.keras
3. Enhancing Vision with Convolutional Neural Networks:
CNN, DNN, python library: SciPy
4. Using Real-world Images:
train_datagen, validation_datagen
" Convolutional Neural Networks in TensorFlow":
1. Exploring a Larger Dataset:
Kaggle Challenge, Keras, ImageDataGenerator
2. Augmentation: A technique to avoid overfitting:
Overfitting, fugmentation,
3. Transfer Learning
4. Multiclass Classifications

"Natural Language Processing in TensorFlow":
1. Sentiment in text:
Kaggle
2. Word embeddings:
.Embedding(), .GlobalAveragePooling1D()
3. Assessments Overdue:
.Embedding(), .Bidirectional(), .LSTM(), .Conv1D(), .GlobalAveragePooling1D(), .GlobalMaxPooling1D(), .GRU()
4. Sequence models and literature:
tf.saved_model.save(), tf.metrics.Mean().reset_states(), model.save_weights()
"Sequences, Time Series and Prediction":
1. Sequences and Prediction:
trend, seasonality_pattern, seasonality, noise, autocorrelation, impulses, naive forecasting, metric: errors, mse, rmse, mae, mape, differencing
2. Deep Neural Networks for Time Series:
model.save()
3. Recurrent Neural Networks for Time Series:
Keras, Lambda layers, RNN, LSTM, tf.keras.backend.clear_session(),
4. Real-world time series data:
Kaggle,


14.MLg_sites


Sites: (14.MLg_sites)

https://www.coursera.org
----------------------------------------------------------------------------------------------
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/have-questions-join-us-on-discourse (have question -> go "Discourse")
----------------------------------------------------------------------------------------------
https://github.com/https-deeplearning-ai/tensorflow-1-public
----------------------------------------------------------------------------------------------
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
----------------------------------------------------------------------------------------------
https://docs.google.com/document/d/1UoKfjNYw33cSu2msPMc9SjytrK0IFuKy7O6kLnh8vng/edit?pli=1 (the Code of Conduct )
----------------------------------------------------------------------------------------------
https://community.deeplearning.ai/login
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform (if you have question, please send form)
----------------------------------------------------------------------------------------------
https://colab.research.google.com
----------------------------------------------------------------------------------------------
https://research.google.com/seedbank (example ML), not working
----------------------------------------------------------------------------------------------
https://research.google.com/colaboratory/faq.html
----------------------------------------------------------------------------------------------
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community:
(1- https://community.deeplearning.ai/login:_) lecture notes
----------------------------------------------------------------------------------------------
https://www.deeplearning.ai/ai-for-everyone/
----------------------------------------------------------------------------------------------
https://github.com/zalandoresearch/fashion-mnist (load data for trainning)
----------------------------------------------------------------------------------------------
https://ai.google/responsibility/responsible-ai-practices/ (that can help us reduce bias.)
----------------------------------------------------------------------------------------------
https://github.com/https-deeplearning-ai/tensorflow-1-public
----------------------------------------------------------------------------------------------
https://resumeworded.com
----------------------------------------------------------------------------------------------
https://su.biginterview.com


15.MLg_1c


(w1) A new Programming Paradigm (15.MLg_1c)

(Новая парадигма программирования)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 15 minutes
Self-study: 57 minutes
Graded tasks (Tasks to be assessed): 2

(w1) Introduction: (15.MLg_1c)

Welcome to this course on going from Basics to Mastery of TensorFlow. We're excited you're here! In Week 1, you'll get a soft introduction to what Machine Learning and Deep Learning are, and how they offer you a new programming paradigm, giving you a new set of tools to open previously unexplored scenarios. All you need to know is some very basic programming skills, and you'll pick the rest up as you go along. To get started, check out the first video, a conversation between Andrew and Laurence that sets the theme for what you'll study.
---------------------------------------------------------------
Добро пожаловать на этот курс по переходу от основ к мастерству TensorFlow. Мы рады, что вы здесь! На неделе 1 вы познакомитесь с тем, что такое машинное обучение и глубокое обучение, и как они предлагают вам новую парадигму программирования, предоставляя вам новый набор инструментов для открытия ранее неисследованных сценариев. Все, что вам нужно знать, это некоторые очень базовые навыки программирования, а остальное вы подберете по ходу дела. Для начала посмотрите первое видео, разговор между Эндрю и Лоуренсом, который задает тему того, что вы будете изучать

(w1) Learning Objectives: (15.MLg_1c)

● Monitor the accuracy of the housing price predictions
● Analyze housing price predictions that come from a single layer ● neural network
●Use TensorFlow to build a single layer neural network for fitting linear models
---------------------------------------------------------------
● Отслеживайте точность прогнозов цен на жилье.
● Анализировать прогнозы цен на жилье, полученные из одного слоя ● Нейронная сеть
● Используйте TensorFlow для создания однослойной нейронной сети для подгонки линейных моделей.

1(w1)-video1: (15.MLg_1c)

1.Introduction A conversation with Andrew Ng:
(0:0) Welcome to TensorFlow, from basics to mastery. Some of you may have taken deep learning or machine learning from me and learned about the amazing things you can now do with deep learning machine learning. One of the best tools you can use to implement these algorithms is TensorFlow. Learning algorithms can be quite complicated, and today, programming frameworks like TensorFlow, PyTorch, caffe, and many others can save you a lot of time. These tools can be complicated and what this set of courses will do is teach you how to use TensorFlow effectively. In order to teach much of these courses, I'm absolutely thrilled to introduce Laurence Moroney. >> Thank you, Andrew. >> He is a developer advocate at Google and has been working on Google AI and TensorFlow. Lawrence has also written over 30 programming books including four sci-fi novels. >> Yeah exactly, I've been busy. I really enjoy writing, but the one thing I enjoy even more is learning and teaching AI. Actually, I've learned from the specializations that you mentioned and I learned from your courses. So it's a real honor to be here with you. >> Thank you. I did not know that you were taking my course as well. Thank you. >> Definitely, so as a big fan, and that's really what got me into AI was, it's actually long story, I started doing AI many, many years ago back when it was things like Prolog and Lisp and all that. But now when we've gotten more into machine learning and deep learning with neural networks, I needed a place to learn, and I actually learned it from your courses, so it's been exciting to be actually coming full circle and now teaching it myself, too.
----------------------------------------------------------------------------------------------
Добро пожаловать на TensorFlow, от основ до мастерства. Некоторые из вас, возможно, прослушали мои курсы по глубокому обучению или машинному обучению и изучаете то, насколько потрясающие вещи вы можете сейчас делать с помощью глубокого и машинного обучения. Одним из лучших инструментов, который можно применять для реализации этих алгоритмов — является TensorFlow. Алгоритмы обучения могут быть довольно сложными, и сегодня программные фреймворки, такие как TensorFlow, PyTorch и многие другие — могут сэкономить вам много времени. Эти инструменты могут быть сложными, и поэтому данный набор курсов научит вас, как эффективно использовать TensorFlow. И в качестве преподавателя большинства их этих курсов я очень рад представить вам Лоренса Мороуни. >> Спасибо, Эндрю. Он является представителем разработчиков в Google и работает в Google AI и TensorFlow. Лоуренс также написал более 30 книг, посвящённых программированию, в том числе, 4 научно-фантастических романа. >> Да точно, пришлось потрудиться. Я очень люблю писать, но одна вещь мне нравится еще больше — это изучение и преподавание ИИ. На самом деле, я изучил материал из специализаций, которые вы упоминали, и я учился на ваших курсах. Так что это настоящая честь — быть здесь с вами. Спасибо. Я не знал, что вы также проходили мой курс. Спасибо. Безусловно, я большой фанат, и на самом деле, этот курс и привел меня в ИИ — это, вообще-то, длинная история. Я начинал работать с ИИ много лет назад, когда были вещи вроде Пролога и Лиспа, и все такое. Но теперь, когда мы погрузились больше в машинное обучение и глубокое изучение с нейронными сетями, мне нужно было где-то учиться, и на самом деле я изучал это на ваших курсах, поэтому это было круто пройти полный круг, и теперь самому это преподавать.

(1:29) Thank you. I actually did not know that. Thank you for sharing that. >> I caught you by surprise. >> Yes. >> [LAUGH] >> So, where the industry is at right now is one of the things that really excites me, because it's just, it's really exploding, right? There's deep learning and machine learning skills are becoming ever more important and opening up whole new scenarios. >> One of the strange things and exciting things about machine learning and AI is that it is no longer just a technical thing limited to the software industry so that everyone in all this - every industry needs to figure this out. >> Yeah, and it's exciting from a developer's perspective because there's a new paradigm, and the new paradigm to me is opening up scenarios that weren't previously possible, things that were too difficult for me to write programs for. And it's like whenever a new paradigm comes, and these new tools come, and it can open up new scenarios, then that opens up great new opportunities. >> Yeah, and I think one of the tragic things today is, even though the whole world sees the promise and the hope of these machine learning AI capabilities changing so many things, the world just doesn't have enough AI developers today. >> Exactly. I mean I've seen surveys of 25, 26 million software developers and maybe 300,000 AI practitioners. So part of my personal passion is to try and turn those 24.7 non-AI practitioners, a significant portion of them into people who can understand AI and who can build the new and exciting things that we can't think of.
----------------------------------------------------------------------------------------------
Спасибо. Я действительно не знал про это. Спасибо за откровенность. >> Я застал вас врасплох. >> Да. [СМЕХ] Современное состояние этой индустрии — это одна действительно впечатляющих меня вещей, т.к. она стремительно развивается, навыки работы с глубоким обучением и машинным обучением становятся все более важными и открывают совершенно новые сценарии. >>Одной из странных и впечатляющих вещей в машинном обучении и в ИИ является то, что оно уже не просто техническая штука, ограниченная индустрией ПО, поэтому в каждой отрасли все должны с этим ознакомиться. >> Да, да, и это интересно с точки зрения разработчика, потому что это новая парадигма и она открывает для меня сценарии, которые не были ранее возможны, вещи, которые были слишком трудны, чтобы их запрограммировать. Чем бы это ни было, когда приходит новая парадигма, и приходят новые инструменты, и это может открыть новые сценарии, то это открывает огромные новые возможности. >> Да, да, и я думаю, одна из неприятных вещей сегодня: даже несмотря на то, что весь мир видит будущее и надежду, которую сулят возможности машинного обучения и ИИ, столь многое меняющие, — при этом в мире на сегодня просто нет достаточного числа ИИ разработчиков. Именно. Я увидел опросники 25, 26 миллионов разработчиков программного обеспечения, и среди них, возможно, 300 000 применяющих ИИ, поэтому частью моей личной мотивации является то, чтобы попытаться захватить эти 24.7 млн тех, кто не использует ИИ, и значительную часть из них превратить в людей, способных разбираться в ИИ и строить новые и захватывающие вещи, о которых мы не можем даже подумать.

(2:57) So I think if you finish this set of courses and learn how to code in TensorFlow, hopefully that will help you do some of this exciting work and maybe become an AI developer. So, in the next video, you will hear Laurence talk about the differences between traditional programming paradigms versus the machine learning, and deep learning programming paradigms. And you'll also hear about how to fit in x to y data relationship, how to fit a straight line to data. So please go on to the next video. >> Thank you.
----------------------------------------------------------------------------------------------
Так что я думаю, если вы закончите этот набор курсов и научитесь писать код в TensorFlow — надеюсь, это поможет вам делать что-то захватывающее, и, возможно, станете разработчиком ИИ. В следующем видео вы услышите, как Лоуренс рассказывает о различиях между традиционной парадигмой программирования и машинным обучением, и о парадигмах глубокого обучения. И вы также услышите о том, как определить взаимосвязь между x и y, как описать данные прямой линией. Так что пожалуйста, следуйте к следующему видео. Спасибо.

2(w1)-Materials for self-study: (15.MLg_1c)

Where to find the notebooks for this course:
All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You can simply click the Open in Colab badge at the top of the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this Github repository under the C1 folder. If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
scikit-learn==1.0.1
pandas==1.1.5
matplotlib==3.2.2
seaborn==0.11.2
----------------------------------------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы можете просто щелкнуть значок «Открыть в Colab» в верхней части неоцененных лабораторных работ, в то время как для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом репозитории Github в папке C1. Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

3(w1)-video2: (15.MLg_1c)

2. A primer in machine learning:
Coding has been the bread and butter for developers since the dawn of computing. We're used to creating applications by breaking down requirements into composable problems that can then be coded against. So for example, if we have to write an application that figures out a stock analytic, maybe the price divided by the ratio, we can usually write code to get the values from a data source, do the calculation and then return the result. Or if we're writing a game we can usually figure out the rules. For example, if the ball hits the brick then the brick should vanish and the ball should rebound. But if the ball falls off the bottom of the screen then maybe the player loses their life. We can represent that with this diagram. Rules and data go in answers come out. Rules are expressed in a programming language and data can come from a variety of sources from local variables all the way up to databases. Machine learning rearranges this diagram where we put answers in data in and then we get rules out. So instead of us as developers figuring out the rules when should the brick be removed, when should the player's life end, or what's the desired analytic for any other concept, what we will do is we can get a bunch of examples for what we want to see and then have the computer figure out the rules. Now, this is particularly valuable for problems that you can't solve by figuring the rules out for yourself. So consider this example, activity recognition. If I'm building a device that detects if somebody is say walking and I have data about their speed, I might write code like this and if they're running well that's a faster speed so I could adapt my code to this and if they're biking, well that's not too bad either. I can adapt my code like this. But then I have to do golf recognition too, now my concept becomes broken. But not only that, doing it by speed alone of course is quite naive. We walk and run at different speeds uphill and downhill and other people walk and run at different speeds to us. So, let's go back to this diagram. Ultimately machine learning is very similar but we're just flipping the axes. So instead of me trying to express the problem as rules when often that isn't even possible, I'll have to compromise. The new paradigm is that I get lots and lots of examples and then I have labels on those examples and I use the data to say this is what walking looks like, this is what running looks like, this is what biking looks like and yes, even this is what golfing looks like. So, then it becomes answers and data in with rules being inferred by the machine. A machine learning algorithm then figures out the specific patterns in each set of data that determines the distinctiveness of each. That's what's so powerful and exciting about this programming paradigm. It's more than just a new way of doing the same old thing. It opens up new possibilities that were infeasible to do before. So in the next few minutes, I'm going to show you the basics of creating a neural network which is the workhorse of doing this type of pattern recognition. A neural network is just a slightly more advanced implementation of machine learning and we call that deep learning. But fortunately it's actually very easy to code. So, we're just going to jump straight into deep learning. We'll start with a simple one and then we'll move on to one that does computer vision in about 10 lines of code. But let's start with a very simple "Hello World" example. So you can see just how everything hangs together.
---------------------------------------------------------------
Программирование кормит разработчиков с момента появления вычислительной техники. Мы привыкли создавать приложения, разбивая требования на составные задачи, которые затем могут быть закодированы. Например, если нам нужно написать приложение, вычисляющее биржевую аналитику, возможно, отношение цены к прибыли, — то обычно мы можем написать код, получающий значения из источника данных, выполняющий вычисления, а затем возвращающий результат. Или, если мы пишем игру, обычно мы можем определить правила. Например, если шарик ударяется о кирпич, то этот кирпич должен исчезнуть, а шарик должен отрикошетить. Но если шарик упадет на нижнюю часть экрана, тогда, возможно, игрок теряет одну жизнь. Мы можем представить это следующей диаграммой. Правила и данные поступают на вход, а ответы получаем на выходе. Правила выражаются на языке программирования, а данные могут приходить из различных источников, начиная с локальных переменных и заканчивая базами данных. Машинное обучение перестраивает эту диаграмму так, что мы подаем ответы и данные на вход, а правила получаем на выходе. Так что уже не мы, как разработчики, выводим правила: когда кирпичик должен быть убран, когда жизнь игрока должна закончиться, или какая нужна аналитика для любого другого концепта. — вместо этого мы можем и будем брать кучу примеров того, что мы хотим видеть, — и затем дадим компьютеру выяснить правила. Это особенно ценно для задач, которые вы не можете решить выведением правил самостоятельно. Рассмотрим такой пример: "распознавание действия". Если я разрабатываю устройство, которое определяет, к примеру, что кто-то идет, и у меня есть данные о его скорости, то я бы мог написать примерно такой код. А если они бегут, то это более высокая скорость, поэтому я мог бы подстроить мой код таким образом, а если они едут на велосипедах, ну, это тоже не так плохо. Я могу переделать код вот так. Но если затем мне нужно будет также распознавать игру в гольф, то моя концепция будет сломана. Не только потому что определять это по одной лишь скорости — довольно наивно. Мы ходим и бегаем с разной скоростью в гору и под гору, а другие люди ходят и бегают со скоростью, отличающейся от нашей. Вернемся к этой диаграмме. В конечном итоге, машинное обучение очень похоже, мы лишь переворачиваем оси. То есть, вместо моих стараний выразить задачу в виде правил, что зачастую вообще невозможно, — я вынужден буду пойти на компромисс. Новая парадигма заключается в том, что я получаю множество примеров, а затем я размечаю их и использую данные, чтобы сказать, что вот так выглядит ходьба, вот так выглядит бег, вот так выглядит катание на велосипеде, и даже — вот так выглядит игра в гольф. Вот так потом это становится ответами и входными данными для правил, выводимых машиной. Затем алгоритм машинного обучения определяет особые шаблоны в каждом наборе данных, определяющие отличия каждого. Вот в чем заключается такая мощь и увлекательность данной парадигмы программирования. Это больше чем просто новый способ делать ту же старую вещь. Это открывает новые возможности, которые было невозможно воплотить раньше. В течении следующих нескольких минут я собираюсь показать вам основы создания нейронной сети, являющейся рабочей лошадкой в распознавании шаблонов такого рода. Нейронная сеть — это просто чуть более продвинутая реализация машинного обучения, мы называем это глубоким обучением. Но, к счастью, это действительно очень легко закодировать. Итак мы сейчас собираемся прыгнуть прямо в глубокое обучение. Мы начнем с простого, и затем мы будем двигаться к тому, что обеспечивает компьютерное зрение примерно 10 строками кода. Но давайте начнем с очень простого примера «Hello World». Таким образом вы сможете увидеть, как все соединяется вместе.

4(w1)-video3: (15.MLg_1c)

3. The ‘Hello World’ of neural networks:
(0:0) Earlier we mentioned that machine learning is all about a computer learning the patterns that distinguish things. Like for activity recognition, it was the pattern of walking, running and biking that can be learned from various sensors on a device. To show how that works, let's take a look at a set of numbers and see if you can determine the pattern between them. Okay, here are the numbers. There's a formula that maps X to Y. Can you spot it? Take a moment.
----------------------------------------------------------------------------------------------
Ранее мы упоминали, что машинное обучение представляет собой изучение компьютером шаблонов, позволяющих отличать вещи друг от друга. Например, для распознавания действий — это был шаблон ходьбы, бега и катания на велосипеде, который может быть выучен на основе данных от различных сенсоров устройства. Чтобы показать, как это работает, давайте взглянем на ряд чисел и посмотрим, сможем ли мы найти в них закономерность. Хорошо, вот они, числа. Есть формула, которая отображает X в Y. Можете определить её? Подумайте минутку.

(0:29) Well, the answer is Y equals 2X minus 1. So whenever you see a Y, it's twice the corresponding X minus 1. If you figured it out for yourself, well done, but how did you do that? How would you think you could figure this out? Maybe you can see that the Y increases by 2 every time the X increases by 1. So it probably looks like Y equals 2X plus or minus something. Then when you saw X equals 0 and Y equals minus 1, so you thought hey that the something is a minus 1, so the answer might be Y equals 2X minus 1. You probably tried that out with a couple of other values and see that it fits. Congratulations, you've just done the basics of machine learning in your head. So let's take a look at it in code now. Okay, here's our first line of code. This is written using Python and TensorFlow and an API in TensorFlow called keras. Keras makes it really easy to define neural networks. A neural network is basically a set of functions which can learn patterns. Don't worry if there were a lot of new concepts here. They will become clear quite quickly as you work through them. The simplest possible neural network is one that has only one neuron in it, and that's what this line of code does. In keras, you use the word dense to define a layer of connected neurons. There's only one dense here. So there's only one layer and there's only one unit in it, so it's a single neuron. Successive layers are defined in sequence, hence the word sequential. But as I've said, there's only one. So you have a single neuron. You define the shape of what's input to the neural network in the first and in this case the only layer, and you can see that our input shape is super simple. It's just one value. You've probably seen that for machine learning, you need to know and use a lot of math, calculus probability and the like. It's really good to understand that as you want to optimize your models but the nice thing for now about TensorFlow and keras is that a lot of that math is implemented for you in functions. There are two function roles that you should be aware of though and these are loss functions and optimizers. This code defines them. I like to think about it this way. The neural network has no idea of the relationship between X and Y, so it makes a guess. Say it guesses Y equals 10X minus 10. It will then use the data that it knows about, that's the set of Xs and Ys that we've already seen to measure how good or how bad its guess was. The loss function measures this and then gives the data to the optimizer which figures out the next guess. So the optimizer thinks about how good or how badly the guess was done using the data from the loss function. Then the logic is that each guess should be better than the one before. As the guesses get better and better, an accuracy approaches 100 percent, the term convergence is used. In this case, the loss is mean squared error and the optimizer is SGD which stands for stochastic gradient descent. If you want to learn more about these particular functions, as well as the other options that might be better in other scenarios, check out the TensorFlow documentation. But for now we're just going to use this. Our next step is to represent the known data. These are the Xs and the Ys that you saw earlier. The np.array is using a Python library called numpy that makes data representation particularly enlists much easier. So here you can see we have one list for the Xs and another one for the Ys. The training takes place in the fit command. Here we're asking the model to figure out how to fit the X values to the Y values. The epochs equals 500 value means that it will go through the training loop 500 times. This training loop is what we described earlier. Make a guess, measure how good or how bad the guesses with the loss function, then use the optimizer and the data to make another guess and repeat this. When the model has finished training, it will then give you back values using the predict method. So it hasn't previously seen 10, and what do you think it will return when you pass it a 10? Now you might think it would return 19 because after all Y equals 2X minus 1, and you think it should be 19. But when you try this in the workbook yourself, you'll see that it will return a value very close to 19 but not exactly 19. Now why do you think that would be? Ultimately there are two main reasons. The first is that you trained it using very little data. There's only six points. Those six points are linear but there's no guarantee that for every X, the relationship will be Y equals 2X minus 1. There's a very high probability that Y equals 19 for X equals 10, but the neural network isn't positive. So it will figure out a realistic value for Y. That's the second main reason. When using neural networks, as they try to figure out the answers for everything, they deal in probability. You'll see that a lot and you'll have to adjust how you handle answers to fit. Keep that in mind as you work through the code. Okay, enough theory. Now let's get hands-on and write the code that we just saw and then we can run it.
----------------------------------------------------------------------------------------------
Итак, ответом будет Y = 2*X - 1. И каждый Y, который вы видите, — это соответствующий X, умноженный на 2, и минус 1. Если вы догадались до этого — молодцы, но как вы это сделали? Как вы думаете, каким образом можно было это определить? Возможно, вы можете увидеть, что Y увеличивается на 2 всякий раз, когда X увеличивается на 1. Поэтому похоже, что Y равен 2*Х, плюс или минус что-то. Затем, когда вы увидели, что X=0, а Y= -1, то подумали, эй, это дополнительное "что-то" равно -1, и тогда ответом будет Y = 2*X - 1. Вы, вероятно, проверили это на паре других значений и убедились, что эта формула подходит. Поздравляю, вы только что выполнили в своей голове то, что является основой машинного обучения. Давайте теперь взглянем на это в коде. Вот наша первая строчка кода. Это код написан с помощью Python и TensorFlow, и API для TensorFlow под названием keras. Keras позволяет очень легко конфигурировать нейронные сети. Нейронная сеть представляет собой набор функций, способный заучивать шаблоны. Не волнуйтесь, если здесь прозвучало много новых понятий. Они довольно быстро станут ясны по мере работы с ними. Простейшая из возможных нейронная сеть состоит всего лишь из одного нейрона, и именно её создаёт данная строчка кода. В keras объект Dense ("плотный") используется для определения слоя связанных нейронов. Здесь есть только один Dense. Поэтому здесь только один слой, и только один элемент (unit) в нём, то есть, это единственный нейрон. Слои, идущие друг за другом, задаются последовательно, отсюда слово Sequential (последовательный). Но как я уже сказал, сейчас здесь только один слой. И у вас есть единственный нейрон. В первую очередь, вы определяете форму того, что будет входом в нейронную сеть, и в нашем случае это единственный слой, и видно, что наша входная форма очень проста — лишь одно значение. Вы, возможно, уже слышали, что для машинного обучения вам нужно знать и использовать много алгебры, математического анализа, теории вероятностей и т.п. Разбираться во всём этом очень полезно, когда вам необходимо оптимизировать ваши модели, но хорошей новостью на данный момент будет то, что в TensorFlow и keras эта математика уже реализована за вас в их функциях. Всё же, есть два вида функций, о которых вам стоит знать — это функции потерь (loss functions) и оптимизаторы (optimizers). Данный код задаёт их. Я предпочитаю думать об этом следующим образом. Нейронная сеть понятия не имеет о взаимосвязи между X и Y, поэтому делает предположение. Скажем, она предполагает, что Y = 10*X - 10. Затем она использует известные ей данные (это набор из пар X и Y, которые мы уже видели), чтобы измерить, насколько хорошим или плохим было предположение. Функция потерь (loss function) как раз это и измеряет, и затем передает данные оптимизатору, который выводит следующее предположение. Таким образом, оптимизатор определяет, насколько хорошо или насколько плохо было сделано предположение, используя данные из функции потерь (loss function). Далее логика в том, что каждое следующее предположение должно быть лучше предыдущего. Так как предположения становятся лучше и лучше, а точность приближается к 100%, то используется термин "сходимость". В нашем случае, потерей (loss) будет среднеквадратическая ошибка (mean_squared_error), а оптимизатором является SGD, т.е., стохастический градиентный спуск [Stochastic Gradient Descent - прим.] Если вы хотите узнать больше об этих конкретных функциях, а также о других опциях, которые могут лучше подойти в других сценариях, — ознакомьтесь с документацией по TensorFlow. Но в данный момент мы собираемся использовать только эти. Наш следующий шаг заключается в представлении известных данных. Это X и Y, которые вы уже видели. np.array использует библиотеку Python под названием NumPy, которая существенно упрощает представление данных — и в частности, списков. Здесь вы видите, что у нас есть отдельный список для X, и еще один для Y. Обучение происходит внутри функции fit. Здесь мы просим модель определить соответствие между значениями X и Y. Параметр epochs=500 означает, что алгоритм пройдет цикл обучения 500 раз. Этот цикл обучения соответствует тому, что мы только что описали. Сделать предположение, измерить, насколько хороши или плохи эти предположения с помощью функции потерь (loss function), затем использовать оптимизатор и данные, чтобы сделать следующее предположение, и повторить всё снова. Когда модель закончила обучение, она затем сможет выдать вам значения, используя метод predict (предсказать). Т.к. она никогда ранее не видела значения 10, то как вы думаете, что она вам вернет, если вы ей передадите 10? Вы можете подумать, что она вернет 19, т.к. все Y ведь соответствуют формуле 2*X-1, и вы думаете, что ответ должен быть 19. Но когда вы попробуете это у себя в workbook, вы увидите, что она вернет значение, очень близкое к 19, но не точно 19. Как вы думаете, почему так могло бы произойти? На то есть две основные причины. Первая — это то, что вы обучали сеть, используя очень мало данных. У нас есть всего шесть точек. Эти шесть точек линейны, но нет гарантии, что для каждого X соответствием будет Y= 2*X - 1. Существует очень высокая вероятность того, что Y = 19 для X = 10, но нейронная сеть не уверена. Поэтому она определит правдоподобное значение для Y. И в этом — вторая основная причина. При использовании нейронных сетей, поскольку они пытаются определить ответы на всё, они имеют дело с вероятностью. Вы увидите достаточно много такого, и вам нужно будет подстраивать то, как вы обрабатываете ответы. Имейте это в виду, работая с кодом. Хорошо, достаточно теории. Теперь давайте попрактикуемся, и напишем код, который мы только что видели, и выполним его.

=======

For resume, profession ML (13.MLg_title)

Profession:
ML Software Engineer; Data Scientist; Automation Engineers; NLP Engineers; AI Experts; Research Scientions; Pre-sales ML Solution Engineer

Keywords deeplearning AI:
" Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning":
1. A new Programming Paradigm:
frameworks TensorFlow, python library: scikit-learn, pandas, matplotlib, seaborn
2. Introduction to Computer Vision:
python library: numpy, matplotlib.pyplot, tf.keras
3. Enhancing Vision with Convolutional Neural Networks:
CNN, DNN, python library: SciPy
4. Using Real-world Images:
train_datagen, validation_datagen
" Convolutional Neural Networks in TensorFlow":
1. Exploring a Larger Dataset:
Kaggle Challenge, Keras, ImageDataGenerator
2. Augmentation: A technique to avoid overfitting:
Overfitting, fugmentation,
3. Transfer Learning
4. Multiclass Classifications

"Natural Language Processing in TensorFlow":
1. Sentiment in text:
Kaggle
2. Word embeddings:
.Embedding(), .GlobalAveragePooling1D()
3. Assessments Overdue:
.Embedding(), .Bidirectional(), .LSTM(), .Conv1D(), .GlobalAveragePooling1D(), .GlobalMaxPooling1D(), .GRU()
4. Sequence models and literature:
tf.saved_model.save(), tf.metrics.Mean().reset_states(), model.save_weights()
"Sequences, Time Series and Prediction":
1. Sequences and Prediction:
trend, seasonality_pattern, seasonality, noise, autocorrelation, impulses, naive forecasting, metric: errors, mse, rmse, mae, mape, differencing
2. Deep Neural Networks for Time Series:
model.save()
3. Recurrent Neural Networks for Time Series:
Keras, Lambda layers, RNN, LSTM, tf.keras.backend.clear_session(),
4. Real-world time series data:
Kaggle,


14.MLg_sites


Sites: (14.MLg_sites)

https://www.coursera.org
----------------------------------------------------------------------------------------------
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/have-questions-join-us-on-discourse (have question -> go "Discourse")
----------------------------------------------------------------------------------------------
https://github.com/https-deeplearning-ai/tensorflow-1-public
----------------------------------------------------------------------------------------------
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
----------------------------------------------------------------------------------------------
https://docs.google.com/document/d/1UoKfjNYw33cSu2msPMc9SjytrK0IFuKy7O6kLnh8vng/edit?pli=1 (the Code of Conduct )
----------------------------------------------------------------------------------------------
https://community.deeplearning.ai/login
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform (if you have question, please send form)
----------------------------------------------------------------------------------------------
https://colab.research.google.com
----------------------------------------------------------------------------------------------
https://research.google.com/seedbank (example ML), not working
----------------------------------------------------------------------------------------------
https://research.google.com/colaboratory/faq.html
----------------------------------------------------------------------------------------------
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community:
(1- https://community.deeplearning.ai/login:_) lecture notes
----------------------------------------------------------------------------------------------
https://www.deeplearning.ai/ai-for-everyone/
----------------------------------------------------------------------------------------------
https://github.com/zalandoresearch/fashion-mnist (load data for trainning)
----------------------------------------------------------------------------------------------
https://ai.google/responsibility/responsible-ai-practices/ (that can help us reduce bias.)
----------------------------------------------------------------------------------------------
https://github.com/https-deeplearning-ai/tensorflow-1-public
----------------------------------------------------------------------------------------------
https://resumeworded.com
----------------------------------------------------------------------------------------------
https://su.biginterview.com


15.MLg_1c


(w1) A new Programming Paradigm (15.MLg_1c)

(Новая парадигма программирования)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 15 minutes
Self-study: 57 minutes
Graded tasks (Tasks to be assessed): 2

(w1) Introduction: (15.MLg_1c)

Welcome to this course on going from Basics to Mastery of TensorFlow. We're excited you're here! In Week 1, you'll get a soft introduction to what Machine Learning and Deep Learning are, and how they offer you a new programming paradigm, giving you a new set of tools to open previously unexplored scenarios. All you need to know is some very basic programming skills, and you'll pick the rest up as you go along. To get started, check out the first video, a conversation between Andrew and Laurence that sets the theme for what you'll study.
---------------------------------------------------------------
Добро пожаловать на этот курс по переходу от основ к мастерству TensorFlow. Мы рады, что вы здесь! На неделе 1 вы познакомитесь с тем, что такое машинное обучение и глубокое обучение, и как они предлагают вам новую парадигму программирования, предоставляя вам новый набор инструментов для открытия ранее неисследованных сценариев. Все, что вам нужно знать, это некоторые очень базовые навыки программирования, а остальное вы подберете по ходу дела. Для начала посмотрите первое видео, разговор между Эндрю и Лоуренсом, который задает тему того, что вы будете изучать

(w1) Learning Objectives: (15.MLg_1c)

● Monitor the accuracy of the housing price predictions
● Analyze housing price predictions that come from a single layer ● neural network
●Use TensorFlow to build a single layer neural network for fitting linear models
---------------------------------------------------------------
● Отслеживайте точность прогнозов цен на жилье.
● Анализировать прогнозы цен на жилье, полученные из одного слоя ● Нейронная сеть
● Используйте TensorFlow для создания однослойной нейронной сети для подгонки линейных моделей.

1(w1)-video1: (15.MLg_1c)

1.Introduction A conversation with Andrew Ng:
(0:0) Welcome to TensorFlow, from basics to mastery. Some of you may have taken deep learning or machine learning from me and learned about the amazing things you can now do with deep learning machine learning. One of the best tools you can use to implement these algorithms is TensorFlow. Learning algorithms can be quite complicated, and today, programming frameworks like TensorFlow, PyTorch, caffe, and many others can save you a lot of time. These tools can be complicated and what this set of courses will do is teach you how to use TensorFlow effectively. In order to teach much of these courses, I'm absolutely thrilled to introduce Laurence Moroney. >> Thank you, Andrew. >> He is a developer advocate at Google and has been working on Google AI and TensorFlow. Lawrence has also written over 30 programming books including four sci-fi novels. >> Yeah exactly, I've been busy. I really enjoy writing, but the one thing I enjoy even more is learning and teaching AI. Actually, I've learned from the specializations that you mentioned and I learned from your courses. So it's a real honor to be here with you. >> Thank you. I did not know that you were taking my course as well. Thank you. >> Definitely, so as a big fan, and that's really what got me into AI was, it's actually long story, I started doing AI many, many years ago back when it was things like Prolog and Lisp and all that. But now when we've gotten more into machine learning and deep learning with neural networks, I needed a place to learn, and I actually learned it from your courses, so it's been exciting to be actually coming full circle and now teaching it myself, too.
----------------------------------------------------------------------------------------------
Добро пожаловать на TensorFlow, от основ до мастерства. Некоторые из вас, возможно, прослушали мои курсы по глубокому обучению или машинному обучению и изучаете то, насколько потрясающие вещи вы можете сейчас делать с помощью глубокого и машинного обучения. Одним из лучших инструментов, который можно применять для реализации этих алгоритмов — является TensorFlow. Алгоритмы обучения могут быть довольно сложными, и сегодня программные фреймворки, такие как TensorFlow, PyTorch и многие другие — могут сэкономить вам много времени. Эти инструменты могут быть сложными, и поэтому данный набор курсов научит вас, как эффективно использовать TensorFlow. И в качестве преподавателя большинства их этих курсов я очень рад представить вам Лоренса Мороуни. >> Спасибо, Эндрю. Он является представителем разработчиков в Google и работает в Google AI и TensorFlow. Лоуренс также написал более 30 книг, посвящённых программированию, в том числе, 4 научно-фантастических романа. >> Да точно, пришлось потрудиться. Я очень люблю писать, но одна вещь мне нравится еще больше — это изучение и преподавание ИИ. На самом деле, я изучил материал из специализаций, которые вы упоминали, и я учился на ваших курсах. Так что это настоящая честь — быть здесь с вами. Спасибо. Я не знал, что вы также проходили мой курс. Спасибо. Безусловно, я большой фанат, и на самом деле, этот курс и привел меня в ИИ — это, вообще-то, длинная история. Я начинал работать с ИИ много лет назад, когда были вещи вроде Пролога и Лиспа, и все такое. Но теперь, когда мы погрузились больше в машинное обучение и глубокое изучение с нейронными сетями, мне нужно было где-то учиться, и на самом деле я изучал это на ваших курсах, поэтому это было круто пройти полный круг, и теперь самому это преподавать.

(1:29) Thank you. I actually did not know that. Thank you for sharing that. >> I caught you by surprise. >> Yes. >> [LAUGH] >> So, where the industry is at right now is one of the things that really excites me, because it's just, it's really exploding, right? There's deep learning and machine learning skills are becoming ever more important and opening up whole new scenarios. >> One of the strange things and exciting things about machine learning and AI is that it is no longer just a technical thing limited to the software industry so that everyone in all this - every industry needs to figure this out. >> Yeah, and it's exciting from a developer's perspective because there's a new paradigm, and the new paradigm to me is opening up scenarios that weren't previously possible, things that were too difficult for me to write programs for. And it's like whenever a new paradigm comes, and these new tools come, and it can open up new scenarios, then that opens up great new opportunities. >> Yeah, and I think one of the tragic things today is, even though the whole world sees the promise and the hope of these machine learning AI capabilities changing so many things, the world just doesn't have enough AI developers today. >> Exactly. I mean I've seen surveys of 25, 26 million software developers and maybe 300,000 AI practitioners. So part of my personal passion is to try and turn those 24.7 non-AI practitioners, a significant portion of them into people who can understand AI and who can build the new and exciting things that we can't think of.
----------------------------------------------------------------------------------------------
Спасибо. Я действительно не знал про это. Спасибо за откровенность. >> Я застал вас врасплох. >> Да. [СМЕХ] Современное состояние этой индустрии — это одна действительно впечатляющих меня вещей, т.к. она стремительно развивается, навыки работы с глубоким обучением и машинным обучением становятся все более важными и открывают совершенно новые сценарии. >>Одной из странных и впечатляющих вещей в машинном обучении и в ИИ является то, что оно уже не просто техническая штука, ограниченная индустрией ПО, поэтому в каждой отрасли все должны с этим ознакомиться. >> Да, да, и это интересно с точки зрения разработчика, потому что это новая парадигма и она открывает для меня сценарии, которые не были ранее возможны, вещи, которые были слишком трудны, чтобы их запрограммировать. Чем бы это ни было, когда приходит новая парадигма, и приходят новые инструменты, и это может открыть новые сценарии, то это открывает огромные новые возможности. >> Да, да, и я думаю, одна из неприятных вещей сегодня: даже несмотря на то, что весь мир видит будущее и надежду, которую сулят возможности машинного обучения и ИИ, столь многое меняющие, — при этом в мире на сегодня просто нет достаточного числа ИИ разработчиков. Именно. Я увидел опросники 25, 26 миллионов разработчиков программного обеспечения, и среди них, возможно, 300 000 применяющих ИИ, поэтому частью моей личной мотивации является то, чтобы попытаться захватить эти 24.7 млн тех, кто не использует ИИ, и значительную часть из них превратить в людей, способных разбираться в ИИ и строить новые и захватывающие вещи, о которых мы не можем даже подумать.

(2:57) So I think if you finish this set of courses and learn how to code in TensorFlow, hopefully that will help you do some of this exciting work and maybe become an AI developer. So, in the next video, you will hear Laurence talk about the differences between traditional programming paradigms versus the machine learning, and deep learning programming paradigms. And you'll also hear about how to fit in x to y data relationship, how to fit a straight line to data. So please go on to the next video. >> Thank you.
----------------------------------------------------------------------------------------------
Так что я думаю, если вы закончите этот набор курсов и научитесь писать код в TensorFlow — надеюсь, это поможет вам делать что-то захватывающее, и, возможно, станете разработчиком ИИ. В следующем видео вы услышите, как Лоуренс рассказывает о различиях между традиционной парадигмой программирования и машинным обучением, и о парадигмах глубокого обучения. И вы также услышите о том, как определить взаимосвязь между x и y, как описать данные прямой линией. Так что пожалуйста, следуйте к следующему видео. Спасибо.

2(w1)-Materials for self-study: (15.MLg_1c)

Where to find the notebooks for this course:
All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You can simply click the Open in Colab badge at the top of the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this Github repository under the C1 folder. If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
scikit-learn==1.0.1
pandas==1.1.5
matplotlib==3.2.2
seaborn==0.11.2
----------------------------------------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы можете просто щелкнуть значок «Открыть в Colab» в верхней части неоцененных лабораторных работ, в то время как для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом репозитории Github в папке C1. Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

3(w1)-video2: (15.MLg_1c)

2. A primer in machine learning:
Coding has been the bread and butter for developers since the dawn of computing. We're used to creating applications by breaking down requirements into composable problems that can then be coded against. So for example, if we have to write an application that figures out a stock analytic, maybe the price divided by the ratio, we can usually write code to get the values from a data source, do the calculation and then return the result. Or if we're writing a game we can usually figure out the rules. For example, if the ball hits the brick then the brick should vanish and the ball should rebound. But if the ball falls off the bottom of the screen then maybe the player loses their life. We can represent that with this diagram. Rules and data go in answers come out. Rules are expressed in a programming language and data can come from a variety of sources from local variables all the way up to databases. Machine learning rearranges this diagram where we put answers in data in and then we get rules out. So instead of us as developers figuring out the rules when should the brick be removed, when should the player's life end, or what's the desired analytic for any other concept, what we will do is we can get a bunch of examples for what we want to see and then have the computer figure out the rules. Now, this is particularly valuable for problems that you can't solve by figuring the rules out for yourself. So consider this example, activity recognition. If I'm building a device that detects if somebody is say walking and I have data about their speed, I might write code like this and if they're running well that's a faster speed so I could adapt my code to this and if they're biking, well that's not too bad either. I can adapt my code like this. But then I have to do golf recognition too, now my concept becomes broken. But not only that, doing it by speed alone of course is quite naive. We walk and run at different speeds uphill and downhill and other people walk and run at different speeds to us. So, let's go back to this diagram. Ultimately machine learning is very similar but we're just flipping the axes. So instead of me trying to express the problem as rules when often that isn't even possible, I'll have to compromise. The new paradigm is that I get lots and lots of examples and then I have labels on those examples and I use the data to say this is what walking looks like, this is what running looks like, this is what biking looks like and yes, even this is what golfing looks like. So, then it becomes answers and data in with rules being inferred by the machine. A machine learning algorithm then figures out the specific patterns in each set of data that determines the distinctiveness of each. That's what's so powerful and exciting about this programming paradigm. It's more than just a new way of doing the same old thing. It opens up new possibilities that were infeasible to do before. So in the next few minutes, I'm going to show you the basics of creating a neural network which is the workhorse of doing this type of pattern recognition. A neural network is just a slightly more advanced implementation of machine learning and we call that deep learning. But fortunately it's actually very easy to code. So, we're just going to jump straight into deep learning. We'll start with a simple one and then we'll move on to one that does computer vision in about 10 lines of code. But let's start with a very simple "Hello World" example. So you can see just how everything hangs together.
---------------------------------------------------------------
Программирование кормит разработчиков с момента появления вычислительной техники. Мы привыкли создавать приложения, разбивая требования на составные задачи, которые затем могут быть закодированы. Например, если нам нужно написать приложение, вычисляющее биржевую аналитику, возможно, отношение цены к прибыли, — то обычно мы можем написать код, получающий значения из источника данных, выполняющий вычисления, а затем возвращающий результат. Или, если мы пишем игру, обычно мы можем определить правила. Например, если шарик ударяется о кирпич, то этот кирпич должен исчезнуть, а шарик должен отрикошетить. Но если шарик упадет на нижнюю часть экрана, тогда, возможно, игрок теряет одну жизнь. Мы можем представить это следующей диаграммой. Правила и данные поступают на вход, а ответы получаем на выходе. Правила выражаются на языке программирования, а данные могут приходить из различных источников, начиная с локальных переменных и заканчивая базами данных. Машинное обучение перестраивает эту диаграмму так, что мы подаем ответы и данные на вход, а правила получаем на выходе. Так что уже не мы, как разработчики, выводим правила: когда кирпичик должен быть убран, когда жизнь игрока должна закончиться, или какая нужна аналитика для любого другого концепта. — вместо этого мы можем и будем брать кучу примеров того, что мы хотим видеть, — и затем дадим компьютеру выяснить правила. Это особенно ценно для задач, которые вы не можете решить выведением правил самостоятельно. Рассмотрим такой пример: "распознавание действия". Если я разрабатываю устройство, которое определяет, к примеру, что кто-то идет, и у меня есть данные о его скорости, то я бы мог написать примерно такой код. А если они бегут, то это более высокая скорость, поэтому я мог бы подстроить мой код таким образом, а если они едут на велосипедах, ну, это тоже не так плохо. Я могу переделать код вот так. Но если затем мне нужно будет также распознавать игру в гольф, то моя концепция будет сломана. Не только потому что определять это по одной лишь скорости — довольно наивно. Мы ходим и бегаем с разной скоростью в гору и под гору, а другие люди ходят и бегают со скоростью, отличающейся от нашей. Вернемся к этой диаграмме. В конечном итоге, машинное обучение очень похоже, мы лишь переворачиваем оси. То есть, вместо моих стараний выразить задачу в виде правил, что зачастую вообще невозможно, — я вынужден буду пойти на компромисс. Новая парадигма заключается в том, что я получаю множество примеров, а затем я размечаю их и использую данные, чтобы сказать, что вот так выглядит ходьба, вот так выглядит бег, вот так выглядит катание на велосипеде, и даже — вот так выглядит игра в гольф. Вот так потом это становится ответами и входными данными для правил, выводимых машиной. Затем алгоритм машинного обучения определяет особые шаблоны в каждом наборе данных, определяющие отличия каждого. Вот в чем заключается такая мощь и увлекательность данной парадигмы программирования. Это больше чем просто новый способ делать ту же старую вещь. Это открывает новые возможности, которые было невозможно воплотить раньше. В течении следующих нескольких минут я собираюсь показать вам основы создания нейронной сети, являющейся рабочей лошадкой в распознавании шаблонов такого рода. Нейронная сеть — это просто чуть более продвинутая реализация машинного обучения, мы называем это глубоким обучением. Но, к счастью, это действительно очень легко закодировать. Итак мы сейчас собираемся прыгнуть прямо в глубокое обучение. Мы начнем с простого, и затем мы будем двигаться к тому, что обеспечивает компьютерное зрение примерно 10 строками кода. Но давайте начнем с очень простого примера «Hello World». Таким образом вы сможете увидеть, как все соединяется вместе.

4(w1)-video3: (15.MLg_1c)

3. The ‘Hello World’ of neural networks:
(0:0) Earlier we mentioned that machine learning is all about a computer learning the patterns that distinguish things. Like for activity recognition, it was the pattern of walking, running and biking that can be learned from various sensors on a device. To show how that works, let's take a look at a set of numbers and see if you can determine the pattern between them. Okay, here are the numbers. There's a formula that maps X to Y. Can you spot it? Take a moment.
----------------------------------------------------------------------------------------------
Ранее мы упоминали, что машинное обучение представляет собой изучение компьютером шаблонов, позволяющих отличать вещи друг от друга. Например, для распознавания действий — это был шаблон ходьбы, бега и катания на велосипеде, который может быть выучен на основе данных от различных сенсоров устройства. Чтобы показать, как это работает, давайте взглянем на ряд чисел и посмотрим, сможем ли мы найти в них закономерность. Хорошо, вот они, числа. Есть формула, которая отображает X в Y. Можете определить её? Подумайте минутку.

(0:29) Well, the answer is Y equals 2X minus 1. So whenever you see a Y, it's twice the corresponding X minus 1. If you figured it out for yourself, well done, but how did you do that? How would you think you could figure this out? Maybe you can see that the Y increases by 2 every time the X increases by 1. So it probably looks like Y equals 2X plus or minus something. Then when you saw X equals 0 and Y equals minus 1, so you thought hey that the something is a minus 1, so the answer might be Y equals 2X minus 1. You probably tried that out with a couple of other values and see that it fits. Congratulations, you've just done the basics of machine learning in your head. So let's take a look at it in code now. Okay, here's our first line of code. This is written using Python and TensorFlow and an API in TensorFlow called keras. Keras makes it really easy to define neural networks. A neural network is basically a set of functions which can learn patterns. Don't worry if there were a lot of new concepts here. They will become clear quite quickly as you work through them. The simplest possible neural network is one that has only one neuron in it, and that's what this line of code does. In keras, you use the word dense to define a layer of connected neurons. There's only one dense here. So there's only one layer and there's only one unit in it, so it's a single neuron. Successive layers are defined in sequence, hence the word sequential. But as I've said, there's only one. So you have a single neuron. You define the shape of what's input to the neural network in the first and in this case the only layer, and you can see that our input shape is super simple. It's just one value. You've probably seen that for machine learning, you need to know and use a lot of math, calculus probability and the like. It's really good to understand that as you want to optimize your models but the nice thing for now about TensorFlow and keras is that a lot of that math is implemented for you in functions. There are two function roles that you should be aware of though and these are loss functions and optimizers. This code defines them. I like to think about it this way. The neural network has no idea of the relationship between X and Y, so it makes a guess. Say it guesses Y equals 10X minus 10. It will then use the data that it knows about, that's the set of Xs and Ys that we've already seen to measure how good or how bad its guess was. The loss function measures this and then gives the data to the optimizer which figures out the next guess. So the optimizer thinks about how good or how badly the guess was done using the data from the loss function. Then the logic is that each guess should be better than the one before. As the guesses get better and better, an accuracy approaches 100 percent, the term convergence is used. In this case, the loss is mean squared error and the optimizer is SGD which stands for stochastic gradient descent. If you want to learn more about these particular functions, as well as the other options that might be better in other scenarios, check out the TensorFlow documentation. But for now we're just going to use this. Our next step is to represent the known data. These are the Xs and the Ys that you saw earlier. The np.array is using a Python library called numpy that makes data representation particularly enlists much easier. So here you can see we have one list for the Xs and another one for the Ys. The training takes place in the fit command. Here we're asking the model to figure out how to fit the X values to the Y values. The epochs equals 500 value means that it will go through the training loop 500 times. This training loop is what we described earlier. Make a guess, measure how good or how bad the guesses with the loss function, then use the optimizer and the data to make another guess and repeat this. When the model has finished training, it will then give you back values using the predict method. So it hasn't previously seen 10, and what do you think it will return when you pass it a 10? Now you might think it would return 19 because after all Y equals 2X minus 1, and you think it should be 19. But when you try this in the workbook yourself, you'll see that it will return a value very close to 19 but not exactly 19. Now why do you think that would be? Ultimately there are two main reasons. The first is that you trained it using very little data. There's only six points. Those six points are linear but there's no guarantee that for every X, the relationship will be Y equals 2X minus 1. There's a very high probability that Y equals 19 for X equals 10, but the neural network isn't positive. So it will figure out a realistic value for Y. That's the second main reason. When using neural networks, as they try to figure out the answers for everything, they deal in probability. You'll see that a lot and you'll have to adjust how you handle answers to fit. Keep that in mind as you work through the code. Okay, enough theory. Now let's get hands-on and write the code that we just saw and then we can run it.
----------------------------------------------------------------------------------------------
Итак, ответом будет Y = 2*X - 1. И каждый Y, который вы видите, — это соответствующий X, умноженный на 2, и минус 1. Если вы догадались до этого — молодцы, но как вы это сделали? Как вы думаете, каким образом можно было это определить? Возможно, вы можете увидеть, что Y увеличивается на 2 всякий раз, когда X увеличивается на 1. Поэтому похоже, что Y равен 2*Х, плюс или минус что-то. Затем, когда вы увидели, что X=0, а Y= -1, то подумали, эй, это дополнительное "что-то" равно -1, и тогда ответом будет Y = 2*X - 1. Вы, вероятно, проверили это на паре других значений и убедились, что эта формула подходит. Поздравляю, вы только что выполнили в своей голове то, что является основой машинного обучения. Давайте теперь взглянем на это в коде. Вот наша первая строчка кода. Это код написан с помощью Python и TensorFlow, и API для TensorFlow под названием keras. Keras позволяет очень легко конфигурировать нейронные сети. Нейронная сеть представляет собой набор функций, способный заучивать шаблоны. Не волнуйтесь, если здесь прозвучало много новых понятий. Они довольно быстро станут ясны по мере работы с ними. Простейшая из возможных нейронная сеть состоит всего лишь из одного нейрона, и именно её создаёт данная строчка кода. В keras объект Dense ("плотный") используется для определения слоя связанных нейронов. Здесь есть только один Dense. Поэтому здесь только один слой, и только один элемент (unit) в нём, то есть, это единственный нейрон. Слои, идущие друг за другом, задаются последовательно, отсюда слово Sequential (последовательный). Но как я уже сказал, сейчас здесь только один слой. И у вас есть единственный нейрон. В первую очередь, вы определяете форму того, что будет входом в нейронную сеть, и в нашем случае это единственный слой, и видно, что наша входная форма очень проста — лишь одно значение. Вы, возможно, уже слышали, что для машинного обучения вам нужно знать и использовать много алгебры, математического анализа, теории вероятностей и т.п. Разбираться во всём этом очень полезно, когда вам необходимо оптимизировать ваши модели, но хорошей новостью на данный момент будет то, что в TensorFlow и keras эта математика уже реализована за вас в их функциях. Всё же, есть два вида функций, о которых вам стоит знать — это функции потерь (loss functions) и оптимизаторы (optimizers). Данный код задаёт их. Я предпочитаю думать об этом следующим образом. Нейронная сеть понятия не имеет о взаимосвязи между X и Y, поэтому делает предположение. Скажем, она предполагает, что Y = 10*X - 10. Затем она использует известные ей данные (это набор из пар X и Y, которые мы уже видели), чтобы измерить, насколько хорошим или плохим было предположение. Функция потерь (loss function) как раз это и измеряет, и затем передает данные оптимизатору, который выводит следующее предположение. Таким образом, оптимизатор определяет, насколько хорошо или насколько плохо было сделано предположение, используя данные из функции потерь (loss function). Далее логика в том, что каждое следующее предположение должно быть лучше предыдущего. Так как предположения становятся лучше и лучше, а точность приближается к 100%, то используется термин "сходимость". В нашем случае, потерей (loss) будет среднеквадратическая ошибка (mean_squared_error), а оптимизатором является SGD, т.е., стохастический градиентный спуск [Stochastic Gradient Descent - прим.] Если вы хотите узнать больше об этих конкретных функциях, а также о других опциях, которые могут лучше подойти в других сценариях, — ознакомьтесь с документацией по TensorFlow. Но в данный момент мы собираемся использовать только эти. Наш следующий шаг заключается в представлении известных данных. Это X и Y, которые вы уже видели. np.array использует библиотеку Python под названием NumPy, которая существенно упрощает представление данных — и в частности, списков. Здесь вы видите, что у нас есть отдельный список для X, и еще один для Y. Обучение происходит внутри функции fit. Здесь мы просим модель определить соответствие между значениями X и Y. Параметр epochs=500 означает, что алгоритм пройдет цикл обучения 500 раз. Этот цикл обучения соответствует тому, что мы только что описали. Сделать предположение, измерить, насколько хороши или плохи эти предположения с помощью функции потерь (loss function), затем использовать оптимизатор и данные, чтобы сделать следующее предположение, и повторить всё снова. Когда модель закончила обучение, она затем сможет выдать вам значения, используя метод predict (предсказать). Т.к. она никогда ранее не видела значения 10, то как вы думаете, что она вам вернет, если вы ей передадите 10? Вы можете подумать, что она вернет 19, т.к. все Y ведь соответствуют формуле 2*X-1, и вы думаете, что ответ должен быть 19. Но когда вы попробуете это у себя в workbook, вы увидите, что она вернет значение, очень близкое к 19, но не точно 19. Как вы думаете, почему так могло бы произойти? На то есть две основные причины. Первая — это то, что вы обучали сеть, используя очень мало данных. У нас есть всего шесть точек. Эти шесть точек линейны, но нет гарантии, что для каждого X соответствием будет Y= 2*X - 1. Существует очень высокая вероятность того, что Y = 19 для X = 10, но нейронная сеть не уверена. Поэтому она определит правдоподобное значение для Y. И в этом — вторая основная причина. При использовании нейронных сетей, поскольку они пытаются определить ответы на всё, они имеют дело с вероятностью. Вы увидите достаточно много такого, и вам нужно будет подстраивать то, как вы обрабатываете ответы. Имейте это в виду, работая с кодом. Хорошо, достаточно теории. Теперь давайте попрактикуемся, и напишем код, который мы только что видели, и выполним его.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
import tensorflow as tf
import numpy as np
from tensorflow import keras

print(tf.__version__)

# Build a simple Sequential model
model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

# Complite the model
model.compile(optimizer='sgd', loss='mean_squared_error')

# Declare model inputs and outputs for training
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

# Train the model
model.fit(xs, ys, epochs=500)

# Make a predition
print(model.predict([10.0]))
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

5(w1)-Intake Survey (Вступительный опрос) (15.MLg_1c)

We would love to learn more about your experience with DeepLearning.AI and with AI in general. Please consider completing the short 3-question survey so we can better serve you!
----------------------------------------------------------------------------------------------
Мы хотели бы узнать больше о вашем опыте использования DeepLearning.AI и ИИ в целом. Пожалуйста, рассмотрите возможность заполнения короткого опроса из 3 вопросов, чтобы мы могли лучше обслуживать вас!

6(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community! (w1) ([ВАЖНО] Есть вопросы, проблемы или идеи? Присоединяйтесь к нашему сообществу!) (15.MLg_1c)

Hello!
We’ve created a community for you to:
Ask for help on assignments and other course content.
Discuss course topics.
Share your knowledge with other learners.
Build your network
Find out about exciting DeepLearning.AI news, events and competitions!
----------------------------------------------------------------------------------------------
Привет!
Мы создали для вас сообщество, чтобы:
Попросите помощи в заданиях и другом содержании курса.
Обсудите темы курса.
Поделитесь своими знаниями с другими учащимися.
Создайте свою сеть
Узнайте о захватывающих новостях, событиях и конкурсах DeepLearning.AI!

New to our community Please click the box below indicating you agree to use the tool responsibly and then click on “Open Tool.”
----------------------------------------------------------------------------------------------
Новое в нашем сообществе Пожалуйста, установите флажок ниже, указывающий, что вы согласны использовать инструмент ответственно, а затем нажмите «Открыть инструмент».
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
----------------------------------------------------------------------------------------------
We created this User Guide for you. (Мы создали это Руководство пользователя для вас.)
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
----------------------------------------------------------------------------------------------
Be sure to check out the Code of Conduct community guidelines.(Обязательно ознакомьтесь с принципами сообщества Кодекса поведения.)
https://docs.google.com/document/d/1UoKfjNYw33cSu2msPMc9SjytrK0IFuKy7O6kLnh8vng/edit?pli=1
----------------------------------------------------------------------------------------------
Having trouble accessing our community Fill out this form to explain your issue and we will get back to you. (Возникли проблемы с доступом к нашему сообществу. Заполните эту форму, чтобы объяснить свою проблему, и мы свяжемся с вами.)
https://community.deeplearning.ai/login
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
----------------------------------------------------------------------------------------------
We hope to see you in our community soon!
- The DeepLearning.AI team

7(w1)-From rules to data (От правил к данным) (15.MLg_1c)

In these videos, you were given an introduction to the concepts and paradigms of Machine Learning and Deep Learning. You saw that the traditional paradigm of expressing rules in a coding language may not always work to solve a problem. As such, applications such as computer vision are very difficult to solve with rules-based programming. Instead, if we feed a computer with enough data that we describe (or label) as what we want it to recognize -- given that computers are really good at processing data and matching patterns -- then we could potentially ‘train’ a system to solve a problem. We saw a super simple example of that: fitting numbers to a line. So now, let’s go through a notebook and execute the code that trains a neural network to learn how a set of numbers make up a line. After that, you will feed the trained network a new data point and see if it correctly predicts the expected value.
----------------------------------------------------------------------------------------------
В этих видеороликах вы познакомились с концепциями и парадигмами машинного обучения и глубокого обучения. Вы видели, что традиционная парадигма выражения правил на языке программирования не всегда может помочь решить проблему. Таким образом, такие приложения, как компьютерное зрение, очень сложно решить с помощью программирования на основе правил. Вместо этого, если мы снабдим компьютер достаточным количеством данных, которые мы описываем (или помечаем) как то, что мы хотим, чтобы он распознавал, учитывая, что компьютеры действительно хороши в обработке данных и сопоставлении шаблонов, то мы потенциально могли бы «обучить» систему решить задачу. Мы видели очень простой пример: подгонка чисел к строке. Итак, теперь давайте просмотрим блокнот и выполним код, обучающий нейронную сеть тому, как набор чисел составляет линию. После этого вы передадите обученной сети новую точку данных и посмотрите, правильно ли она предсказывает ожидаемое значение.

8(w1)-video4: (15.MLg_1c)

4. Working through ‘Hello World’ in TensorFlow and Python:

(0:0) In the previous section, you saw some details behind the concept and paradigms of machine learning. You saw how it was a change from rules-based expression using code to getting data, labeling that data, and then having a neural network figure out the patterns that bring about the rules. You looked through a very simple example that took some x and y values and figured out the relationship between them. Okay, now you're going to get hands-on with writing this code for yourself. Now you don't need a development environment to do it, and one way that you can use it is to use it right in the browser with something called Google Colaboratory. If you're familiar with Jupyter Notebooks in Python, you'll be right at home, and of course, you can use Jupyter Notebooks too. Otherwise, consider Colab to be an environment that runs in the browser that lets you run, edit, and inspect your Python code. It's really cool for learning with. If you want more details about it, check out this video on YouTube. Here is the Colab environment that I'm using with the Notebook for this lesson loaded into it. I'll step through the lesson first, and then you can go and try it out for yourself. You can run the code by clicking the play button in a code block. Make sure you run each block in order or you might get some bugs. In this block, I am importing and setting up TensorFlow, Keras, and NumPy. Next, I'll define the neural network as we discussed. It's one layer, with one neuron, and one input value. Now I'm going to compile the neural network using the loss function and the optimizer. Remember, these help the neural network guess the pattern, measure how well or how badly the guess performed, before trying again on the next epoch, and slowly getting more accurate. Here's where we give it the data, where we have a known x and unknown corresponding y, and we want to figure out the relationship between them. These are fed in using NumPy arrays. Here's where we do the training and the machine learns the patterns. We're asking the model to fit the x's to the y's and it will try for 500 epochs. Each epoch is where it makes a guess, uses the loss function to figure out how well or how badly it did, and then use the optimizer to make another guess. When it's run, keep an eye on the loss on the right-hand side. Remember, it knows the correct answer for the values we've fed in, so it can compare it's guess against them. When I start, my loss is quite high, i.e the guess wasn't that great. But epoch by epoch, you can see the loss getting lower and lower. So the neural network is getting closer to spotting the relationship. By the time 500 epochs have transpired, the loss is really, really small, meaning that for this data, it has come really close to figuring out the relationship between x and y. So let's see what happens if we give it an x that it hadn't previously seen. In this case, 10. What do you think the answer will be? As you can see, it ends up as 18.98, very close to 19 but not quite 19. Do you remember the reasons why? Check back to the lesson in the previous video to see the answer to this.
----------------------------------------------------------------------------------------------
В предыдущей части вы увидели некоторые детали, стоящие за идеей и парадигмой машинного обучения. Вы видели что это был переход от кода, использующего выражения, основанные на правилах — к получению данных, разметке этих данных и последующему использованию нейронной сети для определения шаблонов, воплощающих правила. Вы просмотрели очень простой пример, где мы брали несколько значений X и Y, и выявляли связь между ними. Ладно, а сейчас мы собираемся попрактиковаться в написании этого кода самостоятельно. Пока вам для этого не понадобится среда разработки. Один из способов так сделать — использовать так называемую Google Colaboratory прямо в браузере. Если вы знакомы с Jupyter Notebooks в Python, вы будете чувствовать себя как дома, — и разумеется, вы можете также пользоваться Jupyter Notebooks. В противном случае, рассматривайте Colab как среду, которая работает в браузере и позволяет вам запускать, редактировать и инспектировать ваш код на Python. С её помощью действительно здорово учиться. Если вы хотите узнать больше об этом инструменте, посмотрите это видео на YouTube. Вот она, среда Colab, которой я пользуюсь, с загруженным в неё блокнотом для данного урока. Сначала я пробегусь по уроку, а затем вы сможете попробовать сделать это самостоятельно. Вы можете выполнить код нажатием кнопки play в блоке code. Убедитесь в том, что вы выполняете каждый блок по порядку. В противном случае, вы можете получить ошибки. В этом блоке я импортирую и настраиваю TensorFlow, Keras и NumPy. Далее я определю нейронную сеть, как мы уже обсуждали. Это один слой из одного нейрона и одно входное значение.

Теперь я собираюсь скомпилировать нейронную сеть, используя функцию потерь и оптимизатор. Помните, что они помогают нейронной сети сделать предположение о шаблоне, измерить, насколько хорошо или плохо построено предположение — прежде чем сделать новую попытку в следующей итерации, постепенно становясь точнее. Вот то место, где мы подаем данные, где у нас есть известные значения X и соответствующие им значения Y, и мы хотим определить связь между ними. Мы их передаём в виде массивов NumPy. В этом месте вы выполняем обучение, и машина изучает шаблоны. Мы просим модель подогнать X к Y и она будет пробовать сделать это на протяжении 500 итераций/эпох. На каждой итерации делается предположение, и применяется функция потерь для выяснения, насколько хорошо или плохо оно было сделано, а затем используется оптимизатор, чтобы построить новое предположение. Когда код работает, следите за ошибкой справа. Помните, сеть знает правильный ответ для значений, которые мы ей скормили, поэтому она может сравнить с ним свое предположение. Вначале ошибка является довольно большой, т.е. предположение не такое уж и хорошее. Но от эпохи к эпохе ошибка становится все меньше и меньше. Так что нейронная сеть становится ближе к выявлению взаимосвязи. К тому моменту, когда истекут 500 эпох, ошибка станет очень и очень маленькой, что означает, что для этих данных сеть подошла очень близко к выявлению взаимосвязи между X и Y. Так давайте же посмотрим, что произойдет, если мы дадим ей такой X, которого она не видела ранее. В данном случае, 10. Как вы думаете, каким будет ответ? Как вы можете видеть, это 18.98. Очень близко к 19, но не точно 19. Помните ли вы причины, почему это так? Чтобы увидеть ответ, снова просмотрите видео предыдущего урока.

=======

5(w1)-Intake Survey (Вступительный опрос) (15.MLg_1c)

We would love to learn more about your experience with DeepLearning.AI and with AI in general. Please consider completing the short 3-question survey so we can better serve you!
----------------------------------------------------------------------------------------------
Мы хотели бы узнать больше о вашем опыте использования DeepLearning.AI и ИИ в целом. Пожалуйста, рассмотрите возможность заполнения короткого опроса из 3 вопросов, чтобы мы могли лучше обслуживать вас!

6(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community! (w1) ([ВАЖНО] Есть вопросы, проблемы или идеи? Присоединяйтесь к нашему сообществу!) (15.MLg_1c)

Hello!
We’ve created a community for you to:
Ask for help on assignments and other course content.
Discuss course topics.
Share your knowledge with other learners.
Build your network
Find out about exciting DeepLearning.AI news, events and competitions!
----------------------------------------------------------------------------------------------
Привет!
Мы создали для вас сообщество, чтобы:
Попросите помощи в заданиях и другом содержании курса.
Обсудите темы курса.
Поделитесь своими знаниями с другими учащимися.
Создайте свою сеть
Узнайте о захватывающих новостях, событиях и конкурсах DeepLearning.AI!

New to our community Please click the box below indicating you agree to use the tool responsibly and then click on “Open Tool.”
----------------------------------------------------------------------------------------------
Новое в нашем сообществе Пожалуйста, установите флажок ниже, указывающий, что вы согласны использовать инструмент ответственно, а затем нажмите «Открыть инструмент».
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
----------------------------------------------------------------------------------------------
We created this User Guide for you. (Мы создали это Руководство пользователя для вас.)
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
----------------------------------------------------------------------------------------------
Be sure to check out the Code of Conduct community guidelines.(Обязательно ознакомьтесь с принципами сообщества Кодекса поведения.)
https://docs.google.com/document/d/1UoKfjNYw33cSu2msPMc9SjytrK0IFuKy7O6kLnh8vng/edit?pli=1
----------------------------------------------------------------------------------------------
Having trouble accessing our community Fill out this form to explain your issue and we will get back to you. (Возникли проблемы с доступом к нашему сообществу. Заполните эту форму, чтобы объяснить свою проблему, и мы свяжемся с вами.)
https://community.deeplearning.ai/login
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
----------------------------------------------------------------------------------------------
We hope to see you in our community soon!
- The DeepLearning.AI team

7(w1)-From rules to data (От правил к данным) (15.MLg_1c)

In these videos, you were given an introduction to the concepts and paradigms of Machine Learning and Deep Learning. You saw that the traditional paradigm of expressing rules in a coding language may not always work to solve a problem. As such, applications such as computer vision are very difficult to solve with rules-based programming. Instead, if we feed a computer with enough data that we describe (or label) as what we want it to recognize -- given that computers are really good at processing data and matching patterns -- then we could potentially ‘train’ a system to solve a problem. We saw a super simple example of that: fitting numbers to a line. So now, let’s go through a notebook and execute the code that trains a neural network to learn how a set of numbers make up a line. After that, you will feed the trained network a new data point and see if it correctly predicts the expected value.
----------------------------------------------------------------------------------------------
В этих видеороликах вы познакомились с концепциями и парадигмами машинного обучения и глубокого обучения. Вы видели, что традиционная парадигма выражения правил на языке программирования не всегда может помочь решить проблему. Таким образом, такие приложения, как компьютерное зрение, очень сложно решить с помощью программирования на основе правил. Вместо этого, если мы снабдим компьютер достаточным количеством данных, которые мы описываем (или помечаем) как то, что мы хотим, чтобы он распознавал, учитывая, что компьютеры действительно хороши в обработке данных и сопоставлении шаблонов, то мы потенциально могли бы «обучить» систему решить задачу. Мы видели очень простой пример: подгонка чисел к строке. Итак, теперь давайте просмотрим блокнот и выполним код, обучающий нейронную сеть тому, как набор чисел составляет линию. После этого вы передадите обученной сети новую точку данных и посмотрите, правильно ли она предсказывает ожидаемое значение.

8(w1)-video4: (15.MLg_1c)

4. Working through ‘Hello World’ in TensorFlow and Python:

(0:0) In the previous section, you saw some details behind the concept and paradigms of machine learning. You saw how it was a change from rules-based expression using code to getting data, labeling that data, and then having a neural network figure out the patterns that bring about the rules. You looked through a very simple example that took some x and y values and figured out the relationship between them. Okay, now you're going to get hands-on with writing this code for yourself. Now you don't need a development environment to do it, and one way that you can use it is to use it right in the browser with something called Google Colaboratory. If you're familiar with Jupyter Notebooks in Python, you'll be right at home, and of course, you can use Jupyter Notebooks too. Otherwise, consider Colab to be an environment that runs in the browser that lets you run, edit, and inspect your Python code. It's really cool for learning with. If you want more details about it, check out this video on YouTube. Here is the Colab environment that I'm using with the Notebook for this lesson loaded into it. I'll step through the lesson first, and then you can go and try it out for yourself. You can run the code by clicking the play button in a code block. Make sure you run each block in order or you might get some bugs. In this block, I am importing and setting up TensorFlow, Keras, and NumPy. Next, I'll define the neural network as we discussed. It's one layer, with one neuron, and one input value. Now I'm going to compile the neural network using the loss function and the optimizer. Remember, these help the neural network guess the pattern, measure how well or how badly the guess performed, before trying again on the next epoch, and slowly getting more accurate. Here's where we give it the data, where we have a known x and unknown corresponding y, and we want to figure out the relationship between them. These are fed in using NumPy arrays. Here's where we do the training and the machine learns the patterns. We're asking the model to fit the x's to the y's and it will try for 500 epochs. Each epoch is where it makes a guess, uses the loss function to figure out how well or how badly it did, and then use the optimizer to make another guess. When it's run, keep an eye on the loss on the right-hand side. Remember, it knows the correct answer for the values we've fed in, so it can compare it's guess against them. When I start, my loss is quite high, i.e the guess wasn't that great. But epoch by epoch, you can see the loss getting lower and lower. So the neural network is getting closer to spotting the relationship. By the time 500 epochs have transpired, the loss is really, really small, meaning that for this data, it has come really close to figuring out the relationship between x and y. So let's see what happens if we give it an x that it hadn't previously seen. In this case, 10. What do you think the answer will be? As you can see, it ends up as 18.98, very close to 19 but not quite 19. Do you remember the reasons why? Check back to the lesson in the previous video to see the answer to this.
----------------------------------------------------------------------------------------------
В предыдущей части вы увидели некоторые детали, стоящие за идеей и парадигмой машинного обучения. Вы видели что это был переход от кода, использующего выражения, основанные на правилах — к получению данных, разметке этих данных и последующему использованию нейронной сети для определения шаблонов, воплощающих правила. Вы просмотрели очень простой пример, где мы брали несколько значений X и Y, и выявляли связь между ними. Ладно, а сейчас мы собираемся попрактиковаться в написании этого кода самостоятельно. Пока вам для этого не понадобится среда разработки. Один из способов так сделать — использовать так называемую Google Colaboratory прямо в браузере. Если вы знакомы с Jupyter Notebooks в Python, вы будете чувствовать себя как дома, — и разумеется, вы можете также пользоваться Jupyter Notebooks. В противном случае, рассматривайте Colab как среду, которая работает в браузере и позволяет вам запускать, редактировать и инспектировать ваш код на Python. С её помощью действительно здорово учиться. Если вы хотите узнать больше об этом инструменте, посмотрите это видео на YouTube. Вот она, среда Colab, которой я пользуюсь, с загруженным в неё блокнотом для данного урока. Сначала я пробегусь по уроку, а затем вы сможете попробовать сделать это самостоятельно. Вы можете выполнить код нажатием кнопки play в блоке code. Убедитесь в том, что вы выполняете каждый блок по порядку. В противном случае, вы можете получить ошибки. В этом блоке я импортирую и настраиваю TensorFlow, Keras и NumPy. Далее я определю нейронную сеть, как мы уже обсуждали. Это один слой из одного нейрона и одно входное значение.

Теперь я собираюсь скомпилировать нейронную сеть, используя функцию потерь и оптимизатор. Помните, что они помогают нейронной сети сделать предположение о шаблоне, измерить, насколько хорошо или плохо построено предположение — прежде чем сделать новую попытку в следующей итерации, постепенно становясь точнее. Вот то место, где мы подаем данные, где у нас есть известные значения X и соответствующие им значения Y, и мы хотим определить связь между ними. Мы их передаём в виде массивов NumPy. В этом месте вы выполняем обучение, и машина изучает шаблоны. Мы просим модель подогнать X к Y и она будет пробовать сделать это на протяжении 500 итераций/эпох. На каждой итерации делается предположение, и применяется функция потерь для выяснения, насколько хорошо или плохо оно было сделано, а затем используется оптимизатор, чтобы построить новое предположение. Когда код работает, следите за ошибкой справа. Помните, сеть знает правильный ответ для значений, которые мы ей скормили, поэтому она может сравнить с ним свое предположение. Вначале ошибка является довольно большой, т.е. предположение не такое уж и хорошее. Но от эпохи к эпохе ошибка становится все меньше и меньше. Так что нейронная сеть становится ближе к выявлению взаимосвязи. К тому моменту, когда истекут 500 эпох, ошибка станет очень и очень маленькой, что означает, что для этих данных сеть подошла очень близко к выявлению взаимосвязи между X и Y. Так давайте же посмотрим, что произойдет, если мы дадим ей такой X, которого она не видела ранее. В данном случае, 10. Как вы думаете, каким будет ответ? Как вы можете видеть, это 18.98. Очень близко к 19, но не точно 19. Помните ли вы причины, почему это так? Чтобы увидеть ответ, снова просмотрите видео предыдущего урока.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
import tensorflow as tf
import numpy as np
from tensorflow import keras

print(tf.__version__)

# Build a simple Sequential model
model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

# Complite the model
model.compile(optimizer='sgd', loss='mean_squared_error')

# Declare model inputs and outputs for training
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

# Train the model
model.fit(xs, ys, epochs=500)

# Make a predition
print(model.predict([10.0]))

   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

9(w1)-video5: (15.MLg_1c)

5. Get started with Google Colaboratory (Coding TensorFlow):
https://colab.research.google.com
+ Cell: Code, Text(MarkDown)
+ code snippets (< >): for example: visualization
+ Text: headings, paragrath, list, even a math formula
+ share: (people name) or copi link -> Save a copy in GitHub gist
+ https://research.google.com/seedbank/ (example ML), not working

10(w1)-FAQs about Google Colab (optional): (15.MLg_1c)

As mentioned earlier, you can use Google Colab to follow along with the coding exercises in this course. The previous video showed a quick intro on how to use this environment and here are some Frequently Asked Questions in case you want to know more.
----------------------------------------------------------------------------------------------
Как упоминалось ранее, вы можете использовать Google Colab, чтобы выполнять упражнения по кодированию в этом курсе. Предыдущее видео показало краткое введение в использование этой среды, и вот несколько часто задаваемых вопросов, если вы хотите узнать больше.
https://research.google.com/colaboratory/faq.html

11(w1)-Try it for yourself (Lab 1): (15.MLg_1c)

Ok, now that you’ve seen the demo:, why don’t you give it a try for yourself? You can download the workbook here.
Now while this might seem very simple, you’ve actually gotten the basics of how neural networks work. You’ll continue to use the same techniques as your applications get more complex.
----------------------------------------------------------------------------------------------
Хорошо, теперь, когда вы видели демоверсию, почему бы вам не попробовать ее самостоятельно? Скачать рабочую тетрадь можно здесь.
Теперь, хотя это может показаться очень простым, вы на самом деле узнали основы работы нейронных сетей. Вы будете продолжать использовать те же методы по мере того, как ваши приложения станут более сложными.
----------------------------------------------------------------------------------------------
Ungraded Lab: The Hello World of Deep Learning with Neural Networks:
Like every first app, you should start with something super simple that shows the overall scaffolding for how your code works. In the case of creating neural networks, one simple case is where it learns the relationship between two numbers. So, for example, if you were writing code for a function like this, you already know the 'rules':
Code:
def hw_function(x):
y = (2 * x) - 1
return y
So how would you train a neural network to do the equivalent task? By using data! By feeding it with a set of x's and y's, it should be able to figure out the relationship between them.
This is obviously a very different paradigm from what you might be used to. So let's step through it piece by piece.
----------------------------------------------------------------------------------------------
Лабораторная работа без оценки: Привет, мир глубокого обучения с нейронными сетями:
Как и в любом первом приложении, вы должны начать с чего-то очень простого, которое показывает общую структуру работы вашего кода. В случае создания нейронных сетей одним простым случаем является изучение связи между двумя числами. Так, например, если вы писали код для такой функции, вы уже знаете «правила»:
Итак, как бы вы обучили нейронную сеть выполнять эквивалентную задачу? Используя данные! Скармливая ему набор x и y, он должен быть в состоянии выяснить взаимосвязь между ними.
Очевидно, что это совсем другая парадигма, чем та, к которой вы, возможно, привыкли. Итак, давайте шаг за шагом.

Imports:
Let's start with the imports. Here, you are importing TensorFlow and calling it tf for convention and ease of use.
You then import a library called numpy which helps to represent data as arrays easily and to optimize numerical operations.
The framework you will use to build a neural network as a sequence of layers is called keras so you will import that too.
Code:
import tensorflow as tf
import numpy as np
from tensorflow import keras
print(tf.__version__)
----------------------------------------------------------------------------------------------
Начнем с импорта. Здесь вы импортируете TensorFlow и называете его tf для удобства и простоты использования.
Затем вы импортируете библиотеку под названием numpy, которая помогает легко представлять данные в виде массивов и оптимизировать числовые операции.
Фреймворк, который вы будете использовать для построения нейронной сети в виде последовательности слоев, называется keras, поэтому вы также импортируете его.
----------------------------------------------------------------------------------------------
Providing the Data:
Next up, you will feed in some data. In this case, you are taking 6 X's and 6 Y's. You can see that the relationship between these is y=2x-1, so where x = -1, y=-3 etc.
The de facto standard way of declaring model inputs and outputs is to use numpy, a Python library that provides lots of array type data structures. You can specify these values by building numpy arrays with np.array().
Code:
# Declare model inputs and outputs for training
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
----------------------------------------------------------------------------------------------
Далее вы вводите некоторые данные. В этом случае вы берете 6 X и 6 Y. Вы можете видеть, что отношение между ними равно y=2x-1, поэтому где x = -1, y=-3 и т. д.
Де-факто стандартным способом объявления входных и выходных данных модели является использование numpy, библиотеки Python, которая предоставляет множество структур данных типа массива. Вы можете указать эти значения, создав массивы numpy с помощью np.array().

Training the Neural Network:
The process of training the neural network, where it 'learns' the relationship between the x's and y's is in the model.fit() call. This is where it will go through the loop we spoke about above: making a guess, measuring how good or bad it is (aka the loss), using the optimizer to make another guess etc. It will do it for the number of epochs you specify. When you run this code, you'll see the loss on the right hand side.
Code:
# Train the model
model.fit(xs, ys, epochs=500)
----------------------------------------------------------------------------------------------
Процесс обучения нейронной сети, когда она «изучает» взаимосвязь между x и y, находится в вызове model.fit(). Здесь он будет проходить через цикл, о котором мы говорили выше: делать предположения, измерять, насколько они хороши или плохи (т. указать. Когда вы запустите этот код, вы увидите потерю справа.
----------------------------------------------------------------------------------------------
Ok, now you have a model that has been trained to learn the relationship between x and y. You can use the model.predict() method to have it figure out the y for a previously unknown x. So, for example, if x=10, what do you think y will be? Take a guess before you run this code:
Code:
# Make a prediction
print(model.predict([10.0]))
----------------------------------------------------------------------------------------------
Хорошо, теперь у вас есть модель, обученная изучать взаимосвязь между x и y. Вы можете использовать метод model.predict(), чтобы вычислить y для ранее неизвестного x. Так, например, если x=10, как вы думаете, каким будет y? Подумайте, прежде чем запускать этот код:
----------------------------------------------------------------------------------------------
You might have thought 19, right? But it ended up being a little under. Why do you think that is?
Remember that neural networks deal with probabilities. So given the data that we fed the model with, it calculated that there is a very high probability that the relationship between x and y is y=2x-1, but with only 6 data points we can't know for sure. As a result, the result for 10 is very close to 19, but not necessarily 19.
As you work with neural networks, you'll see this pattern recurring. You will almost always deal with probabilities, not certainties, and will do a little bit of coding to figure out what the result is based on the probabilities, particularly when it comes to classification.
----------------------------------------------------------------------------------------------
Вы могли подумать, что 19, верно? Но в итоге оказался немного ниже. Как вы думаете, почему?
Помните, что нейронные сети имеют дело с вероятностями. Таким образом, учитывая данные, которые мы передали модели, она подсчитала, что существует очень высокая вероятность того, что отношение между x и y составляет y = 2x-1, но только с 6 точками данных мы не можем знать наверняка. В результате результат для 10 очень близок к 19, но не обязательно 19.
Когда вы будете работать с нейронными сетями, вы увидите повторяющийся паттерн. Вы почти всегда будете иметь дело с вероятностями, а не с уверенностью, и будете немного кодировать, чтобы выяснить, какой результат основан на вероятностях, особенно когда дело доходит до классификации.

12(w1)- video6: (15.MLg_1c)

Week 1 Quiz1:
1) What is the difference between traditional programming and Machine Learning?:
1. Machine learning identifies complex acnivitiesc such as golf, while traditional programming is better suited to simpler activities such as walking.
2.(+) In traditional programming, a programmer has to formulate or cade rules manually, whereas, in Machine Learning, the algorithm automatically formulates the rules from the data.
2) What do we call the process of telling the computer what the data represents (i.e. this data is for walking, this data is for running)?:
1. Learning the Data.
2. Programming the Data(1).
3. Categorizing the Data(2).
4. (+)Labelling the Data
3) What is Dense layer?:
1. A single neuron.
2. An amount of mass occupying a volume.
3.(+) A layer of connected neurons.
4. A layer of disconnected neurons
4)How do you measure how good the current 'guess' is?:
1.(+) Using the Loss function.
2. Figuring out if you win or lose
3. Training a neural network
5) What does the optimizer do?:
1. Measures how good the current guess is
2.(+) Generates a new and improved guess.
3. Figures out how to efficiently compile your code
4. Decides to stop training a neural network
6) What is Convergence?:
1. An analysis that corresponds too closely or exactly to a particular set of data
2. A programming API for AI
3.(+) The process of getting very close to the correct answer.
4. A dramatic increase in loss
7) What does model.fit do?:
1. it optimizes an existing model
2. It determines if your activity is good for your body
3.(+) It trains the neural network to fit one set of values to another.
4. It makes a model fit available memory

13(w1) Lecture Notes Week 1: (15.MLg_1c)

Lecture Notes Week 1:
The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login:
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community:
----------------------------------------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций.
здесь.
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте инструкциям.здесь, затем вернитесь на эту страницу.
----------------------------------------------------------------------------------------------
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai:
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode:
----------------------------------------------------------------------------------------------
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons.
DeepLearning.AI делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
Остальные сведения о лицензии см.

14(w1) Weekly Assignment - Tour First Neaural Network: (15.MLg_1c)

Assignment Troubleshooting Tips:
(Советы по устранению неполадок с заданиями)
Here are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
(Ниже приведены некоторые общие рекомендации перед отправкой заданий в рамках этого курса. Пожалуйста, имейте это в виду не только для задания этой недели, но и для следующих:)
1. Make sure to save your work before clicking the Submit button. If not, you might get an error message like in the code cell below. Remember that everything that you need to fill in within the graded functions is initialized to None.
(Обязательно сохраните свою работу, прежде чем нажимать кнопку «Отправить». В противном случае вы можете получить сообщение об ошибке, как в ячейке кода ниже. Помните, что все, что вам нужно заполнить в оценочных функциях, инициализируется значением None.)
----------------------------------------------------------------------------------------------
Failed test case: x has incorrect type.
Expected:
some.Type,
but got:
<class 'NoneType'>.
----------------------------------------------------------------------------------------------
2. Please do not rename the notebook. The grader will look for the original filename and its associated metadata so you should work on the file that is automatically opened when you click the Launch Notebook button. If you try to submit a renamed notebook, then you might also get an error like the one shown above.
(Пожалуйста, не переименовывайте блокнот. Оценщик будет искать исходное имя файла и связанные с ним метаданные, поэтому вам следует работать с файлом, который автоматически открывается при нажатии кнопки «Запустить блокнот». Если вы попытаетесь отправить переименованный блокнот, вы также можете получить сообщение об ошибке, подобное показанному выше.)
----------------------------------------------------------------------------------------------
3. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
(Пожалуйста, не изменяйте код вне тегов START CODE HERE и END CODE HERE. Ваше решение должно быть размещено только между этими маркерами, чтобы гарантировать успешное оценивание. Изменение параметров функции и других тестовых ячеек, скорее всего, приведет к поломке оценщика. Если вы хотите поэкспериментировать с ними, вы можете сделать это после того, как успешно пройдете задание.)
----------------------------------------------------------------------------------------------
4. After following the tips above and the grader still gives you 0/100, it's possible that the metadata needed for grading is corrupted. Please get a new lab notebook by refreshing your workspace (instructions here). Then copy your solutions into the new notebook. Make sure that all cells still run as expected then resubmit.
https://www.coursera.org/learn/introduction-tensorflow/supplement/M20rh/optional-downloading-your-notebook-and-refreshing-your-workspace
(Если после выполнения приведенных выше советов оценщик по-прежнему выдает вам 0/100, возможно, метаданные, необходимые для оценивания, повреждены. Пожалуйста, получите новую лабораторную тетрадь, обновив рабочее пространство (инструкции здесь). Затем скопируйте свои решения в новый блокнот. Убедитесь, что все ячейки по-прежнему работают должным образом, а затем повторите отправку.)
----------------------------------------------------------------------------------------------
5. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by following the instructions here. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/have-questions-join-us-on-discourse
(Если у вас есть дополнительные вопросы, создайте тему в сообществе Discourse, а не на дискуссионных форумах Coursera. Вы можете присоединиться, следуя инструкциям здесь. Вы получите помощь там быстрее, потому что несколько наставников и ваших однокурсников следят за сообщениями. Просто убедитесь, что тема создана в правильной категории курса.)
---------------------------------------------------------------------------------------------

(Optional) Downloading your Notebook and Refreshing your Workspace:
This course uses Coursera Labs to provide a notebook environment and to grade your work. There might be some instances where you need to download your notebooks or refresh your workspace to start from scratch. This reading item outlines the steps to do so.
(Этот курс использует Coursera Labs для предоставления среды ноутбука и оценки вашей работы. В некоторых случаях вам может потребоваться загрузить свои записные книжки или обновить рабочую область, чтобы начать с нуля. Этот пункт для чтения описывает шаги для этого.)
----------------------------------------------------------------------------------------------
Downloading your Notebook:
In case you need to download your notebook for troubleshooting or running in your local environment, you can follow these simple steps:
From the Menu Bar of the notebook you are working on, Click File → Save and Checkpoint to first save your progress.
Click File → Download as → Notebook (.ipynb). This should start downloading the file into your local machine.
(Загрузка вашего ноутбука:
Если вам нужно загрузить блокнот для устранения неполадок или запуска в локальной среде, вы можете выполнить следующие простые действия:
В строке меню блокнота, над которым вы работаете, нажмите «Файл» → «Сохранить» и «Проверить», чтобы сначала сохранить свой прогресс.
Нажмите «Файл» → «Загрузить как» → «Блокнот» (.ipynb). Это должно начать загрузку файла на ваш локальный компьютер.)
----------------------------------------------------------------------------------------------
Refreshing your Workspace:
This will come in handy whenever you need to start from scratch, fetch the latest version of the assignment, or run into a 404 error.
Open the notebook from the classroom.
After the notebook opens up, click File → Open
When your workspace opens, tick the check box before your notebook file. After it is selected, press Shutdown. The icon beside the filename should turn from green to gray.
Tick the checkbox again and this time choose Rename and enter any filename other than the original. For example, C4W1_Assignment.ipynb (original) → C4W1_Assignment_v2.ipynb
(Optional) Tick the checkbox of any other file that you want to get a fresh copy of (e.g. dataset files that you might have manipulated irreversibly). Then click Delete . You can also opt to Rename or Download each file individually in case you want to keep them before deleting.
Click on the Help button on the top right of the page.
Click the Get latest version button.
Click the Update Lab button. The page will refresh and you should now see the latest version of the notebook.
(Обновление вашего рабочего пространства:
Это пригодится, когда вам нужно начать с нуля, получить последнюю версию задания или столкнуться с ошибкой 404.
Откройте тетрадь из класса.
После того, как блокнот откроется, нажмите «Файл» → «Открыть».
Когда откроется ваше рабочее пространство, установите флажок перед файлом записной книжки. После того, как он выбран, нажмите «Выключить». Значок рядом с именем файла должен изменить цвет с зеленого на серый.
Установите флажок еще раз и на этот раз выберите «Переименовать» и введите любое имя файла, отличное от исходного. Например, C4W1_Assignment.ipynb (исходный) → C4W1_Assignment_v2.ipynb
(Необязательно) Отметьте любой другой файл, свежую копию которого вы хотите получить (например, файлы наборов данных, которые вы, возможно, необратимо изменили). Затем нажмите Удалить . Вы также можете выбрать «Переименовать» или «Загрузить» каждый файл по отдельности, если хотите сохранить их перед удалением.
Нажмите кнопку «Справка» в правом верхнем углу страницы.
Нажмите кнопку Получить последнюю версию.
Нажмите кнопку Обновить лабораторию. Страница обновится, и теперь вы должны увидеть последнюю версию записной книжки.)

15(w1) HomeWork Housing Prices (video7) (15.MLg_1c)

Great! You’ve come a long way already! Now it’s time to do an exercise in programming:. Earlier this week, you saw a ‘Hello World’ in Machine Learning that predicted a relationship between X and Y values. These were purely arbitrary but it did give you the template for how you can solve more difficult problems. For this exercise, you will write code that does a similar task -- in this case, predicting house prices based on a simple linear equation.
To submit your assignment for grading, please click the Submit Assignment button inside the notebook.
(Большой! Вы уже прошли долгий путь! Теперь пришло время выполнить упражнение по программированию. Ранее на этой неделе вы видели «Hello World» в машинном обучении, которое предсказывало взаимосвязь между значениями X и Y. Они были совершенно произвольными, но они давали вам образец того, как вы можете решать более сложные проблемы. В этом упражнении вы напишете код, выполняющий аналогичную задачу — в данном случае прогноз цен на жилье на основе простого линейного уравнения.
Чтобы отправить задание на оценку, нажмите кнопку «Отправить задание» внутри блокнота.)
----------------------------------------------------------------------------------------------
IMPORTANT FOR SUCCESSFUL GRADING:
- Don't forget to save your notebook before submitting!
- Don't delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
(ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не забудьте сохранить блокнот перед отправкой!
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.)
----------------------------------------------------------------------------------------------
If you have any questions about the assignments in this course, kindly ask for assistance in our community. If you haven't yet, please click here and follow the instructions so you can join!
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community-on-discourse
(Если у вас есть какие-либо вопросы о заданиях в этом курсе, пожалуйста, обратитесь за помощью в наше сообщество. Если вы еще этого не сделали, нажмите здесь и следуйте инструкциям, чтобы присоединиться!)

Week 1 Assignment: Housing Prices:
In this exercise you'll try to build a neural network that predicts the price of a house according to a simple formula.
Imagine that house pricing is as easy as:
A house has a base cost of 50k, and every additional bedroom adds a cost of 50k. This will make a 1 bedroom house cost 100k, a 2 bedroom house cost 150k etc.
How would you create a neural network that learns this relationship so that it would predict a 7 bedroom house as costing close to 400k etc.
Hint: Your network might work better if you scale the house price down. You don't have to give the answer 400...it might be better to create something that predicts the number 4, and then your answer is in the 'hundreds of thousands' etc.
(Неделя 1 Задание: Цены на жилье
В этом упражнении вы попробуете построить нейронную сеть, которая предсказывает цену дома по простой формуле.
Представьте, что оценить дом так же просто, как:
Базовая стоимость дома составляет 50 тысяч, а каждая дополнительная спальня добавляет 50 тысяч. Таким образом, дом с 1 спальней будет стоить 100 тысяч, дом с 2 спальнями — 150 тысяч и т.
Как бы вы создали нейронную сеть, которая изучает эту взаимосвязь, чтобы она предсказывала, что дом с 7 спальнями будет стоить около 400 тысяч и т. д.
Подсказка: ваша сеть может работать лучше, если вы снизите цену дома. Вам не нужно давать ответ 400... может быть лучше создать что-то, что предсказывает число 4, и тогда ваш ответ будет в «сотнях тысяч» и т. д.)
----------------------------------------------------------------------------------------------
NOTE: To prevent errors from the autograder, you are not allowed to edit or delete non-graded cells in this notebook . Please only put your solutions in between the ### START CODE HERE and ### END CODE HERE code comments, and also refrain from adding any new cells. Once you have passed this assignment and want to experiment with any of the non-graded code, you may follow the instructions at the bottom of this notebook.
(ПРИМЕЧАНИЕ. Во избежание ошибок автооценщика вам не разрешено редактировать или удалять неоцененные ячейки в этой записной книжке. Пожалуйста, помещайте свои решения только между комментариями кода ### START CODE HERE и ### END CODE HERE, а также воздержитесь от добавления каких-либо новых ячеек. После того как вы выполнили это задание и хотите поэкспериментировать с любым неоцениваемым кодом, вы можете следовать инструкциям в нижней части этой записной книжки.)

If everything went as expected you should see a prediction value very close to 4:. **If not, try adjusting your code before submitting the assignment.** Notice that you can play around with the value of `new_x` to get different predictions. In general you should see that the network was able to learn the linear relationship between `x` and `y`, so if you use a value of 8.0 you should get a prediction close to 4.5 and so on.
(Если все прошло так, как ожидалось, вы должны увидеть значение прогноза, очень близкое к 4. **Если нет, попробуйте изменить свой код перед отправкой задания.** Обратите внимание, что вы можете поиграть со значением `new_x`, чтобы получить разные прогнозы. В целом вы должны увидеть, что сеть смогла изучить линейную зависимость между `x` и `y`, поэтому, если вы используете значение 8,0, вы должны получить прогноз, близкий к 4,5 и так далее.)

=======

9(w1)-video5: (15.MLg_1c)

5. Get started with Google Colaboratory (Coding TensorFlow):
https://colab.research.google.com
+ Cell: Code, Text(MarkDown)
+ code snippets (< >): for example: visualization
+ Text: headings, paragrath, list, even a math formula
+ share: (people name) or copi link -> Save a copy in GitHub gist
+ https://research.google.com/seedbank/ (example ML), not working

10(w1)-FAQs about Google Colab (optional): (15.MLg_1c)

As mentioned earlier, you can use Google Colab to follow along with the coding exercises in this course. The previous video showed a quick intro on how to use this environment and here are some Frequently Asked Questions in case you want to know more.
----------------------------------------------------------------------------------------------
Как упоминалось ранее, вы можете использовать Google Colab, чтобы выполнять упражнения по кодированию в этом курсе. Предыдущее видео показало краткое введение в использование этой среды, и вот несколько часто задаваемых вопросов, если вы хотите узнать больше.
https://research.google.com/colaboratory/faq.html

11(w1)-Try it for yourself (Lab 1): (15.MLg_1c)

Ok, now that you’ve seen the demo:, why don’t you give it a try for yourself? You can download the workbook here.
Now while this might seem very simple, you’ve actually gotten the basics of how neural networks work. You’ll continue to use the same techniques as your applications get more complex.
----------------------------------------------------------------------------------------------
Хорошо, теперь, когда вы видели демоверсию, почему бы вам не попробовать ее самостоятельно? Скачать рабочую тетрадь можно здесь.
Теперь, хотя это может показаться очень простым, вы на самом деле узнали основы работы нейронных сетей. Вы будете продолжать использовать те же методы по мере того, как ваши приложения станут более сложными.
----------------------------------------------------------------------------------------------
Ungraded Lab: The Hello World of Deep Learning with Neural Networks:
Like every first app, you should start with something super simple that shows the overall scaffolding for how your code works. In the case of creating neural networks, one simple case is where it learns the relationship between two numbers. So, for example, if you were writing code for a function like this, you already know the 'rules':
Code:
def hw_function(x):
y = (2 * x) - 1
return y
So how would you train a neural network to do the equivalent task? By using data! By feeding it with a set of x's and y's, it should be able to figure out the relationship between them.
This is obviously a very different paradigm from what you might be used to. So let's step through it piece by piece.
----------------------------------------------------------------------------------------------
Лабораторная работа без оценки: Привет, мир глубокого обучения с нейронными сетями:
Как и в любом первом приложении, вы должны начать с чего-то очень простого, которое показывает общую структуру работы вашего кода. В случае создания нейронных сетей одним простым случаем является изучение связи между двумя числами. Так, например, если вы писали код для такой функции, вы уже знаете «правила»:
Итак, как бы вы обучили нейронную сеть выполнять эквивалентную задачу? Используя данные! Скармливая ему набор x и y, он должен быть в состоянии выяснить взаимосвязь между ними.
Очевидно, что это совсем другая парадигма, чем та, к которой вы, возможно, привыкли. Итак, давайте шаг за шагом.

Imports:
Let's start with the imports. Here, you are importing TensorFlow and calling it tf for convention and ease of use.
You then import a library called numpy which helps to represent data as arrays easily and to optimize numerical operations.
The framework you will use to build a neural network as a sequence of layers is called keras so you will import that too.
Code:
import tensorflow as tf
import numpy as np
from tensorflow import keras
print(tf.__version__)
----------------------------------------------------------------------------------------------
Начнем с импорта. Здесь вы импортируете TensorFlow и называете его tf для удобства и простоты использования.
Затем вы импортируете библиотеку под названием numpy, которая помогает легко представлять данные в виде массивов и оптимизировать числовые операции.
Фреймворк, который вы будете использовать для построения нейронной сети в виде последовательности слоев, называется keras, поэтому вы также импортируете его.
----------------------------------------------------------------------------------------------
Providing the Data:
Next up, you will feed in some data. In this case, you are taking 6 X's and 6 Y's. You can see that the relationship between these is y=2x-1, so where x = -1, y=-3 etc.
The de facto standard way of declaring model inputs and outputs is to use numpy, a Python library that provides lots of array type data structures. You can specify these values by building numpy arrays with np.array().
Code:
# Declare model inputs and outputs for training
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
----------------------------------------------------------------------------------------------
Далее вы вводите некоторые данные. В этом случае вы берете 6 X и 6 Y. Вы можете видеть, что отношение между ними равно y=2x-1, поэтому где x = -1, y=-3 и т. д.
Де-факто стандартным способом объявления входных и выходных данных модели является использование numpy, библиотеки Python, которая предоставляет множество структур данных типа массива. Вы можете указать эти значения, создав массивы numpy с помощью np.array().

Training the Neural Network:
The process of training the neural network, where it 'learns' the relationship between the x's and y's is in the model.fit() call. This is where it will go through the loop we spoke about above: making a guess, measuring how good or bad it is (aka the loss), using the optimizer to make another guess etc. It will do it for the number of epochs you specify. When you run this code, you'll see the loss on the right hand side.
Code:
# Train the model
model.fit(xs, ys, epochs=500)
----------------------------------------------------------------------------------------------
Процесс обучения нейронной сети, когда она «изучает» взаимосвязь между x и y, находится в вызове model.fit(). Здесь он будет проходить через цикл, о котором мы говорили выше: делать предположения, измерять, насколько они хороши или плохи (т. указать. Когда вы запустите этот код, вы увидите потерю справа.
----------------------------------------------------------------------------------------------
Ok, now you have a model that has been trained to learn the relationship between x and y. You can use the model.predict() method to have it figure out the y for a previously unknown x. So, for example, if x=10, what do you think y will be? Take a guess before you run this code:
Code:
# Make a prediction
print(model.predict([10.0]))
----------------------------------------------------------------------------------------------
Хорошо, теперь у вас есть модель, обученная изучать взаимосвязь между x и y. Вы можете использовать метод model.predict(), чтобы вычислить y для ранее неизвестного x. Так, например, если x=10, как вы думаете, каким будет y? Подумайте, прежде чем запускать этот код:
----------------------------------------------------------------------------------------------
You might have thought 19, right? But it ended up being a little under. Why do you think that is?
Remember that neural networks deal with probabilities. So given the data that we fed the model with, it calculated that there is a very high probability that the relationship between x and y is y=2x-1, but with only 6 data points we can't know for sure. As a result, the result for 10 is very close to 19, but not necessarily 19.
As you work with neural networks, you'll see this pattern recurring. You will almost always deal with probabilities, not certainties, and will do a little bit of coding to figure out what the result is based on the probabilities, particularly when it comes to classification.
----------------------------------------------------------------------------------------------
Вы могли подумать, что 19, верно? Но в итоге оказался немного ниже. Как вы думаете, почему?
Помните, что нейронные сети имеют дело с вероятностями. Таким образом, учитывая данные, которые мы передали модели, она подсчитала, что существует очень высокая вероятность того, что отношение между x и y составляет y = 2x-1, но только с 6 точками данных мы не можем знать наверняка. В результате результат для 10 очень близок к 19, но не обязательно 19.
Когда вы будете работать с нейронными сетями, вы увидите повторяющийся паттерн. Вы почти всегда будете иметь дело с вероятностями, а не с уверенностью, и будете немного кодировать, чтобы выяснить, какой результат основан на вероятностях, особенно когда дело доходит до классификации.

12(w1)- video6: (15.MLg_1c)

Week 1 Quiz1:
1) What is the difference between traditional programming and Machine Learning?:
1. Machine learning identifies complex acnivitiesc such as golf, while traditional programming is better suited to simpler activities such as walking.
2.(+) In traditional programming, a programmer has to formulate or cade rules manually, whereas, in Machine Learning, the algorithm automatically formulates the rules from the data.
2) What do we call the process of telling the computer what the data represents (i.e. this data is for walking, this data is for running)?:
1. Learning the Data.
2. Programming the Data(1).
3. Categorizing the Data(2).
4. (+)Labelling the Data
3) What is Dense layer?:
1. A single neuron.
2. An amount of mass occupying a volume.
3.(+) A layer of connected neurons.
4. A layer of disconnected neurons
4)How do you measure how good the current 'guess' is?:
1.(+) Using the Loss function.
2. Figuring out if you win or lose
3. Training a neural network
5) What does the optimizer do?:
1. Measures how good the current guess is
2.(+) Generates a new and improved guess.
3. Figures out how to efficiently compile your code
4. Decides to stop training a neural network
6) What is Convergence?:
1. An analysis that corresponds too closely or exactly to a particular set of data
2. A programming API for AI
3.(+) The process of getting very close to the correct answer.
4. A dramatic increase in loss
7) What does model.fit do?:
1. it optimizes an existing model
2. It determines if your activity is good for your body
3.(+) It trains the neural network to fit one set of values to another.
4. It makes a model fit available memory

13(w1) Lecture Notes Week 1: (15.MLg_1c)

Lecture Notes Week 1:
The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login:
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community:
----------------------------------------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций.
здесь.
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте инструкциям.здесь, затем вернитесь на эту страницу.
----------------------------------------------------------------------------------------------
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai:
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode:
----------------------------------------------------------------------------------------------
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons.
DeepLearning.AI делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
Остальные сведения о лицензии см.

14(w1) Weekly Assignment - Tour First Neaural Network: (15.MLg_1c)

Assignment Troubleshooting Tips:
(Советы по устранению неполадок с заданиями)
Here are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
(Ниже приведены некоторые общие рекомендации перед отправкой заданий в рамках этого курса. Пожалуйста, имейте это в виду не только для задания этой недели, но и для следующих:)
1. Make sure to save your work before clicking the Submit button. If not, you might get an error message like in the code cell below. Remember that everything that you need to fill in within the graded functions is initialized to None.
(Обязательно сохраните свою работу, прежде чем нажимать кнопку «Отправить». В противном случае вы можете получить сообщение об ошибке, как в ячейке кода ниже. Помните, что все, что вам нужно заполнить в оценочных функциях, инициализируется значением None.)
----------------------------------------------------------------------------------------------
Failed test case: x has incorrect type.
Expected:
some.Type,
but got:
<class 'NoneType'>.
----------------------------------------------------------------------------------------------
2. Please do not rename the notebook. The grader will look for the original filename and its associated metadata so you should work on the file that is automatically opened when you click the Launch Notebook button. If you try to submit a renamed notebook, then you might also get an error like the one shown above.
(Пожалуйста, не переименовывайте блокнот. Оценщик будет искать исходное имя файла и связанные с ним метаданные, поэтому вам следует работать с файлом, который автоматически открывается при нажатии кнопки «Запустить блокнот». Если вы попытаетесь отправить переименованный блокнот, вы также можете получить сообщение об ошибке, подобное показанному выше.)
----------------------------------------------------------------------------------------------
3. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
(Пожалуйста, не изменяйте код вне тегов START CODE HERE и END CODE HERE. Ваше решение должно быть размещено только между этими маркерами, чтобы гарантировать успешное оценивание. Изменение параметров функции и других тестовых ячеек, скорее всего, приведет к поломке оценщика. Если вы хотите поэкспериментировать с ними, вы можете сделать это после того, как успешно пройдете задание.)
----------------------------------------------------------------------------------------------
4. After following the tips above and the grader still gives you 0/100, it's possible that the metadata needed for grading is corrupted. Please get a new lab notebook by refreshing your workspace (instructions here). Then copy your solutions into the new notebook. Make sure that all cells still run as expected then resubmit.
https://www.coursera.org/learn/introduction-tensorflow/supplement/M20rh/optional-downloading-your-notebook-and-refreshing-your-workspace
(Если после выполнения приведенных выше советов оценщик по-прежнему выдает вам 0/100, возможно, метаданные, необходимые для оценивания, повреждены. Пожалуйста, получите новую лабораторную тетрадь, обновив рабочее пространство (инструкции здесь). Затем скопируйте свои решения в новый блокнот. Убедитесь, что все ячейки по-прежнему работают должным образом, а затем повторите отправку.)
----------------------------------------------------------------------------------------------
5. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by following the instructions here. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/have-questions-join-us-on-discourse
(Если у вас есть дополнительные вопросы, создайте тему в сообществе Discourse, а не на дискуссионных форумах Coursera. Вы можете присоединиться, следуя инструкциям здесь. Вы получите помощь там быстрее, потому что несколько наставников и ваших однокурсников следят за сообщениями. Просто убедитесь, что тема создана в правильной категории курса.)
---------------------------------------------------------------------------------------------

(Optional) Downloading your Notebook and Refreshing your Workspace:
This course uses Coursera Labs to provide a notebook environment and to grade your work. There might be some instances where you need to download your notebooks or refresh your workspace to start from scratch. This reading item outlines the steps to do so.
(Этот курс использует Coursera Labs для предоставления среды ноутбука и оценки вашей работы. В некоторых случаях вам может потребоваться загрузить свои записные книжки или обновить рабочую область, чтобы начать с нуля. Этот пункт для чтения описывает шаги для этого.)
----------------------------------------------------------------------------------------------
Downloading your Notebook:
In case you need to download your notebook for troubleshooting or running in your local environment, you can follow these simple steps:
From the Menu Bar of the notebook you are working on, Click File → Save and Checkpoint to first save your progress.
Click File → Download as → Notebook (.ipynb). This should start downloading the file into your local machine.
(Загрузка вашего ноутбука:
Если вам нужно загрузить блокнот для устранения неполадок или запуска в локальной среде, вы можете выполнить следующие простые действия:
В строке меню блокнота, над которым вы работаете, нажмите «Файл» → «Сохранить» и «Проверить», чтобы сначала сохранить свой прогресс.
Нажмите «Файл» → «Загрузить как» → «Блокнот» (.ipynb). Это должно начать загрузку файла на ваш локальный компьютер.)
----------------------------------------------------------------------------------------------
Refreshing your Workspace:
This will come in handy whenever you need to start from scratch, fetch the latest version of the assignment, or run into a 404 error.
Open the notebook from the classroom.
After the notebook opens up, click File → Open
When your workspace opens, tick the check box before your notebook file. After it is selected, press Shutdown. The icon beside the filename should turn from green to gray.
Tick the checkbox again and this time choose Rename and enter any filename other than the original. For example, C4W1_Assignment.ipynb (original) → C4W1_Assignment_v2.ipynb
(Optional) Tick the checkbox of any other file that you want to get a fresh copy of (e.g. dataset files that you might have manipulated irreversibly). Then click Delete . You can also opt to Rename or Download each file individually in case you want to keep them before deleting.
Click on the Help button on the top right of the page.
Click the Get latest version button.
Click the Update Lab button. The page will refresh and you should now see the latest version of the notebook.
(Обновление вашего рабочего пространства:
Это пригодится, когда вам нужно начать с нуля, получить последнюю версию задания или столкнуться с ошибкой 404.
Откройте тетрадь из класса.
После того, как блокнот откроется, нажмите «Файл» → «Открыть».
Когда откроется ваше рабочее пространство, установите флажок перед файлом записной книжки. После того, как он выбран, нажмите «Выключить». Значок рядом с именем файла должен изменить цвет с зеленого на серый.
Установите флажок еще раз и на этот раз выберите «Переименовать» и введите любое имя файла, отличное от исходного. Например, C4W1_Assignment.ipynb (исходный) → C4W1_Assignment_v2.ipynb
(Необязательно) Отметьте любой другой файл, свежую копию которого вы хотите получить (например, файлы наборов данных, которые вы, возможно, необратимо изменили). Затем нажмите Удалить . Вы также можете выбрать «Переименовать» или «Загрузить» каждый файл по отдельности, если хотите сохранить их перед удалением.
Нажмите кнопку «Справка» в правом верхнем углу страницы.
Нажмите кнопку Получить последнюю версию.
Нажмите кнопку Обновить лабораторию. Страница обновится, и теперь вы должны увидеть последнюю версию записной книжки.)

15(w1) HomeWork Housing Prices (video7) (15.MLg_1c)

Great! You’ve come a long way already! Now it’s time to do an exercise in programming:. Earlier this week, you saw a ‘Hello World’ in Machine Learning that predicted a relationship between X and Y values. These were purely arbitrary but it did give you the template for how you can solve more difficult problems. For this exercise, you will write code that does a similar task -- in this case, predicting house prices based on a simple linear equation.
To submit your assignment for grading, please click the Submit Assignment button inside the notebook.
(Большой! Вы уже прошли долгий путь! Теперь пришло время выполнить упражнение по программированию. Ранее на этой неделе вы видели «Hello World» в машинном обучении, которое предсказывало взаимосвязь между значениями X и Y. Они были совершенно произвольными, но они давали вам образец того, как вы можете решать более сложные проблемы. В этом упражнении вы напишете код, выполняющий аналогичную задачу — в данном случае прогноз цен на жилье на основе простого линейного уравнения.
Чтобы отправить задание на оценку, нажмите кнопку «Отправить задание» внутри блокнота.)
----------------------------------------------------------------------------------------------
IMPORTANT FOR SUCCESSFUL GRADING:
- Don't forget to save your notebook before submitting!
- Don't delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
(ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не забудьте сохранить блокнот перед отправкой!
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.)
----------------------------------------------------------------------------------------------
If you have any questions about the assignments in this course, kindly ask for assistance in our community. If you haven't yet, please click here and follow the instructions so you can join!
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community-on-discourse
(Если у вас есть какие-либо вопросы о заданиях в этом курсе, пожалуйста, обратитесь за помощью в наше сообщество. Если вы еще этого не сделали, нажмите здесь и следуйте инструкциям, чтобы присоединиться!)

Week 1 Assignment: Housing Prices:
In this exercise you'll try to build a neural network that predicts the price of a house according to a simple formula.
Imagine that house pricing is as easy as:
A house has a base cost of 50k, and every additional bedroom adds a cost of 50k. This will make a 1 bedroom house cost 100k, a 2 bedroom house cost 150k etc.
How would you create a neural network that learns this relationship so that it would predict a 7 bedroom house as costing close to 400k etc.
Hint: Your network might work better if you scale the house price down. You don't have to give the answer 400...it might be better to create something that predicts the number 4, and then your answer is in the 'hundreds of thousands' etc.
(Неделя 1 Задание: Цены на жилье
В этом упражнении вы попробуете построить нейронную сеть, которая предсказывает цену дома по простой формуле.
Представьте, что оценить дом так же просто, как:
Базовая стоимость дома составляет 50 тысяч, а каждая дополнительная спальня добавляет 50 тысяч. Таким образом, дом с 1 спальней будет стоить 100 тысяч, дом с 2 спальнями — 150 тысяч и т.
Как бы вы создали нейронную сеть, которая изучает эту взаимосвязь, чтобы она предсказывала, что дом с 7 спальнями будет стоить около 400 тысяч и т. д.
Подсказка: ваша сеть может работать лучше, если вы снизите цену дома. Вам не нужно давать ответ 400... может быть лучше создать что-то, что предсказывает число 4, и тогда ваш ответ будет в «сотнях тысяч» и т. д.)
----------------------------------------------------------------------------------------------
NOTE: To prevent errors from the autograder, you are not allowed to edit or delete non-graded cells in this notebook . Please only put your solutions in between the ### START CODE HERE and ### END CODE HERE code comments, and also refrain from adding any new cells. Once you have passed this assignment and want to experiment with any of the non-graded code, you may follow the instructions at the bottom of this notebook.
(ПРИМЕЧАНИЕ. Во избежание ошибок автооценщика вам не разрешено редактировать или удалять неоцененные ячейки в этой записной книжке. Пожалуйста, помещайте свои решения только между комментариями кода ### START CODE HERE и ### END CODE HERE, а также воздержитесь от добавления каких-либо новых ячеек. После того как вы выполнили это задание и хотите поэкспериментировать с любым неоцениваемым кодом, вы можете следовать инструкциям в нижней части этой записной книжки.)

If everything went as expected you should see a prediction value very close to 4:. **If not, try adjusting your code before submitting the assignment.** Notice that you can play around with the value of `new_x` to get different predictions. In general you should see that the network was able to learn the linear relationship between `x` and `y`, so if you use a value of 8.0 you should get a prediction close to 4.5 and so on.
(Если все прошло так, как ожидалось, вы должны увидеть значение прогноза, очень близкое к 4. **Если нет, попробуйте изменить свой код перед отправкой задания.** Обратите внимание, что вы можете поиграть со значением `new_x`, чтобы получить разные прогнозы. В целом вы должны увидеть, что сеть смогла изучить линейную зависимость между `x` и `y`, поэтому, если вы используете значение 8,0, вы должны получить прогноз, близкий к 4,5 и так далее.)

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# grader-required-cell

import tensorflow as tf
import numpy as np

# grader-required-cell

# GRADED FUNCTION: house_model
def house_model():
    ### START CODE HERE
    
    # Define input and output tensors with the values for houses with 1 up to 6 bedrooms
    # Hint: Remember to explictly set the dtype as float
    xs = np.array([1.0, 2.0, 3.0, 4.0,       5.0,      6.0], dtype=float)
    ys = np.array([1.0, 1.5, 2.0, (3.5-0.5), (4.0-1), (4.5-1.2)], dtype=float)
    
    # Define your model (should be a model with 1 dense layer and 1 unit)
    # Note: you can use `tf.keras` instead of `keras`
    model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])])
    
    # Compile your model
    # Set the optimizer to Stochastic Gradient Descent
    # and use Mean Squared Error as the loss function
    model.compile(optimizer='sgd', loss='mean_squared_error')
    
    # Train your model for 1000 epochs by feeding the i/o tensors
    model.fit(xs, ys, shuffle=True, epochs=1000)
    
    ### END CODE HERE
    return model

# grader-required-cell

# Get your trained model
model = house_model()

# grader-required-cell

new_x = 7.0
prediction = model.predict([new_x])[0]
print(prediction)

[4.0094547]
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

16(w1) Week 1 Resources (15.MLg_1c)

That brings you to the end of what you need to look at for Week 1. If you’re eager to learn more, before we go to Week 2, there are some great resources you can check out:
(Это подводит вас к концу того, что вам нужно изучить в течение недели 1. Если вы хотите узнать больше, прежде чем мы перейдем к неделе 2, есть несколько отличных ресурсов, которые вы можете проверить:)
----------------------------------------------------------------------------------------------
- AI For Everyone is a non-technical course that will help you understand many of the AI technologies we will discuss later in this course, and help you spot opportunities in applying this technology to solve your problems.
https://www.deeplearning.ai/ai-for-everyone/
- TensorFlow is available at TensorFlow.org, and video updates from the TensorFlow team are at youtube.com/tensorflow
(ИИ для всех — это нетехнический курс, который поможет вам понять многие технологии ИИ, которые мы обсудим позже в этом курсе, и поможет вам определить возможности применения этой технологии для решения ваших проблем.
https://www.deeplearning.ai/ai-for-everyone/
TensorFlow доступен на TensorFlow.org, а видеообновления от команды TensorFlow — на youtube.com/tensorflow.)
----------------------------------------------------------------------------------------------
Play with a neural network right in the browser at http://playground.tensorflow.org. See if you can figure out the parameters to get the neural network to pattern match to the desired groups. The spiral is particularly challenging!
(Играйте с нейронной сетью прямо в браузере на http://playground.tensorflow.org. Посмотрите, сможете ли вы определить параметры, чтобы заставить нейронную сеть сопоставлять шаблоны с нужными группами. Спираль особенно сложна!)

NEXT week_2 (15.MLg_1c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2) Introduction to Computer Vision (15.MLg_1c)

(Введение в компьютерное зрение)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 15 minutes
Self-study: 1,46 hour
Graded tasks (Tasks to be assessed): 2

(w2) Introduction: (15.MLg_1c)

Welcome to week 2 of the course! In week 1 you learned all about how Machine Learning and Deep Learning is a new programming paradigm. This week you’re going to take that to the next level by beginning to solve problems of computer vision with just a few lines of code! Check out this conversation between Laurence and Andrew where they discuss it and introduce you to Computer Vision!
---------------------------------------------------------------
Добро пожаловать на вторую неделю курса! На первой неделе вы узнали все о том, что машинное обучение и глубокое обучение — это новая парадигма программирования. На этой неделе вы перейдете на следующий уровень, начав решать проблемы компьютерного зрения всего несколькими строками кода! Посмотрите этот разговор между Лоуренсом и Эндрю, где они обсуждают это и знакомят вас с Computer Vision!

(w2) Learning Objectives: (15.MLg_1c)

● Use callback functions for tracking model loss and accuracy during training
● Make predictions on how the layer size affects network predictions and training speed
● Implement pixel value normalization to speed up network training
● Build a multilayer neural network for classifying the Fashion MNIST image dataset
---------------------------------------------------------------
● Используйте функции обратного вызова для отслеживания потерь и точности модели во время обучения.
● Делайте прогнозы о том, как размер слоя влияет на прогнозы сети и скорость обучения.
● Реализуйте нормализацию значений пикселей, чтобы ускорить обучение сети.
● Создайте многослойную нейронную сеть для классификации набора данных изображений Fashion MNIST.

1(w2)-video1: (15.MLg_1c)

So in that lesson, we just saw the basics of the new programming paradigm that comes with machine learning and deep learning, and how instead of like expressing rules in a programming language, we can start getting data and using labeled data to open up new scenarios like activity recognition. Then for a little bit of fun, we actually started doing our first piece of code. We built a super simple neural network that fit data like an x and y data onto a line but that was just "Hello, World". Right, Andrew? So fitting straight lines seems like the "Hello, world" most basic implementation learning algorithm. But one of the most amazing things about machine learning is that, that core of the idea of fitting the x and y relationship is what lets us do amazing things like, have computers look at the picture and do activity recognition, or look at the picture and tell us, is this a dress, or a pair of pants, or a pair of shoes really hard for humans, and amazing that computers can now use this to do these things as well. Right, like computer vision is a really hard problem to solve, right? Because you're saying like dress or shoes. It's like how would I write rules for that? How would I say, if this pixel then it's a shoe, if that pixel then its a dress. It's really hard to do, so the labeled samples are the right way to go. Yeah. One of the non-intuitive things about vision is that it's so easy for a person to look at you and say, you're wearing a shirt, it's so hard for a computer to figure it out. Because it's so easy for humans to recognize objects, it's almost difficult to understand why this is a complicated thing for a computer to do. What the computer has to do is look at all numbers, all the pixel brightness value, saying look at all of these numbers saying, these numbers correspond to a black shirt, and it's amazing that with machine and deep learning computers are getting really good at this. Right, so it's like with the code that we just used in the previous lesson as you mentioned, it provides a template for everything that we can do with deep learning by designing a Neural network in the layers to be able to recognize patterns like this. So maybe we can do that with clothes recognition today. What do you think? Yeah. So in the next video, you'll learn how to write code to take this paradigm you've already saw in a previous video, but to now apply it to recognizing clothes from labeled data. Please go on to the next video.
---------------------------------------------------------------
В прошлом уроке мы рассмотрели основы новой парадигмы программирования, вытекающей из машинного обучения и глубокого обучения, и увидели, как вместо выражения правил на языке программирования — мы можем начать собирать данные и использовать размеченные данные, что открывает новые сценарии, такие как распознавание действий. Затем, чтобы немного развлечься, мы начали писать наш первый фрагмент кода. Мы создали очень простую нейронную сеть, подгоняющую наши данные, X и Y под прямую линию, но это было лишь "Hello, World". Правильно, Эндрю? Да, подгонка под прямые линии — что-то вроде "Hello, World", самая простая реализация алгоритма обучения. Но одна из наиболее удивительных вещей в машинном обучении состоит в том, что сама идея подгонки взаимосвязи между X и Y позволяет нам делать удивительные вещи, например, заставить компьютер взять картинку и распознавать действия, изображенные на ней. Или смотреть на картинку и говорить нам, изображено ли здесь платье, или пара брюк, или пара обуви — и это тяжело для людей, и замечательно, что компьютеры могут сейчас, используя это, также делать эти вещи. Верно, например, компьютерное зрение — действительно трудная в решении задача, так? Потому что вы говорите, платье или обувь. А как бы я написал правила для этого? Как мне это сказать: если вот такой пиксел, тогда это обувь, а если вот такой, то это одежда? Это очень трудно сделать, поэтому размеченные образцы — это верное направление. Да. Одна из неочевидных вещей в компьютерном зрении — это то, что для человека очень просто взглянуть на вас и сказать: "на вас одета футболка", а для компьютера очень сложно определить это. И поскольку человеку так легко распознать объекты, то сложно понять, почему это же это так сложно сделать компьютеру. Компьютер вынужден изучать все числа, яркости всех пикселов, и глядя на все эти цифры, сказать: "эти числа соответствуют черной футболке". И удивительно, что с помощью машинного и глубокого обучения компьютеры довольно хорошо с этим справляются. Верно, это что-то наподобие кода, который мы недавно использовали, в предыдущем уроке. Как вы упоминали он предоставляет заготовку для всего, что мы можем делать с помощью глубокого обучения, проектируя слои нейронной сети, чтобы иметь возможность распознавать образы, как этот. Так что, возможно, сегодня мы сможем это сделать для распознавания одежды. Как вы думаете? Да. Поэтому в следующем видео вы научитесь тому, как писать код, применяя ту же парадигму, которую вы уже видели в предыдущем видео, но сейчас применить ее к распознаванию одежды по размеченным данным. Приглашаем вас перейти к следующему видео.

2(w2)-video2: (15.MLg_1c)

In the previous lesson, you learned what the machine learning paradigm is and how you use data and labels and have a computer in fair the rules between them for you. You looked at a very simple example where it figured out the relationship between two sets of numbers. Let's now take this to the next level by solving a real problem, computer vision. Computer vision is the field of having a computer understand and label what is present in an image. Consider this slide. When you look at it, you can interpret what a shirt is or what a shoe is, but how would you program for that? If an extra terrestrial who had never seen clothing walked into the room with you, how would you explain the shoes to him? It's really difficult, if not impossible to do right? And it's the same problem with computer vision. So one way to solve that is to use lots of pictures of clothing and tell the computer what that's a picture of and then have the computer figure out the patterns that give you the difference between a shoe, and a shirt, and a handbag, and a coat. That's what you're going to learn how to do in this section. Fortunately, there's a data set called Fashion MNIST which gives a 70 thousand images spread across 10 different items of clothing. These images have been scaled down to 28 by 28 pixels. Now usually, the smaller the better because the computer has less processing to do. But of course, you need to retain enough information to be sure that the features and the object can still be distinguished. If you look at this slide you can still tell the difference between shirts, shoes, and handbags. So this size does seem to be ideal, and it makes it great for training a neural network. The images are also in gray scale, so the amount of information is also reduced. Each pixel can be represented in values from zero to 255 and so it's only one byte per pixel. With 28 by 28 pixels in an image, only 784 bytes are needed to store the entire image. Despite that, we can still see what's in the image and in this case, it's an ankle boot, right?
---------------------------------------------------------------
В предыдущем уроке вы узнали, что представляет из себя парадигма машинного обучения? и как использовать данные и метки, как заставить компьютер вывести за вас связывающие их правила. Вы увидели очень простой пример, где выявлялась взаимосвязь между двумя наборами чисел. Давайте теперь выведем это на следующий уровень, решая реальную задачу компьютерного зрения. Компьютерное зрение — это область, где компьютер понимает и отмечает то, что присутствует на картинке. Рассмотрим этот слайд. Когда вы смотрите на него, вы можете распознать, где рубашка, где обувь, — но как бы вы это запрограммировали? Если вместе с вами в комнате оказался пришелец, который никогда не видел верхнюю одежду, то какое бы вы ему дали описание обуви? Это действительно трудно сделать, если вообще возможно, верно? И та же самая проблема стоит перед компьютерным зрением. Одним из способов решить ее — использовать множество картинок одежды, и сказать компьютеру, что на каком изображении, а затем дать компьютеру выявить шаблоны, позволяющие различать обувь, рубашку, сумочку и пальто. Как это сделать, вы и узнаете в данном разделе. К счастью, у нас есть набор данных под названием Fashion MNIST, в котором содержится 70 тысяч изображений, охватывающих 10 различных предметов одежды. Эти изображения уменьшены до размера 28х28 пикселей. Как правило, чем меньше — тем лучше, потому что компьютеру придётся выполнять меньше вычислений. Но, конечно, вам нужно сохранить достаточно информации, чтобы гарантировать, что признаки объектов по-прежнему различимы. Если вы взглянете на этот слайд, то все еще можете провести различие между футболками, обувью и сумочками. Так что этот размер выглядит идеальным, и это делает его отлично подходящим для обучения нейронной сети. Кроме того, изображения полутоновые, то есть, количество информации здесь также снижается. Каждый пиксел может быть представлен значениями от 0 до 255, то есть, всего один байт на пиксел. Для изображения 28 на 28 пикселов нам необходимо всего 784 байта, чтобы сохранить все изображение. Несмотря на это, нам все еще видно, что изображено на картинке — и в данном случае, это ботинок, верно?

3(w2) Exploring how to use data: (15.MLg_1c)

(Изучение того, как использовать данные)
Machine Learning depends on having good data to train a system with. In the previous video, you were given a scenario to train a system to recognize fashion images. The data comes from a dataset called Fashion MNIST, and you can learn more about it on GitHub
here. In the next video, you’ll see how to load that data and prepare it for training.
https://github.com/zalandoresearch/fashion-mnist
---------------------------------------------------------------
Машинное обучение зависит от наличия хороших данных для обучения системы. В предыдущем видео вам дали сценарий обучения системы распознаванию фэшн-изображений. Данные поступают из набора данных под названием Fashion MNIST, и вы можете узнать больше о нем на GitHub.
здесь. В следующем видео вы увидите, как загрузить эти данные и подготовить их к обучению.

4(w2)-video3: (15.MLg_1c)

So what will handling this look like in code? In the previous lesson, you learned about TensorFlow and Keras, and how to define a super simple neural network with them. In this lesson, you're going to use them to go a little deeper but the overall API should look familiar. The one big difference will be in the data. The last time you had your six pairs of numbers, so you could hard code it. This time you have to load 70,000 images off the disk, so there'll be a bit of code to handle that. Fortunately, it's still quite simple because Fashion-MNIST is available as a data set with an API call in TensorFlow. We simply declare an object of type MNIST loading it from the Keras database. On this object, if we call the load data method, it will return four lists to us. That's the training data, the training labels, the testing data, and the testing labels. Now, what are these you might ask? Well, when building a neural network like this, it's a nice strategy to use some of your data to train the neural network and similar data that the model hasn't yet seen to test how good it is at recognizing the images. So in the Fashion-MNIST data set, 60,000 of the 70,000 images are used to train the network, and then 10,000 images, one that it hasn't previously seen, can be used to test just how good or how bad it is performing. So this code will give you those sets. Then, each set has data, the images themselves and labels and that's what the image is actually of. So for example, the training data will contain images like this one, and a label that describes the image like this. While this image is an ankle boot, the label describing it is the number nine. Now, why do you think that might be? There's two main reasons. First, of course, is that computers do better with numbers than they do with texts. Second, importantly, is that this is something that can help us reduce bias. If we labeled it as an ankle boot, we would be of course biasing towards English speakers. But with it being a numeric label, we can then refer to it in our appropriate language be it English, Chinese, Japanese, or here, even Irish Gaelic.
---------------------------------------------------------------
Итак, как же будет выглядеть эта обработка в коде? В предыдущем уроке вы узнали о TensorFlow и Keras, и как собрать сверхпростую нейронную сеть с их помощью. В этом уроке мы немного углубимся, но общий API будет быть вам знаком. Единственная большая разница будет в данных. В прошлый раз у вас было шесть пар чисел, поэтому их можно было захардкодить. На этот раз вам нужно будет загрузить 70,000 изображений с диска, поэтому здесь будет немного кода, который этим займется. К счастью, это все еще довольно просто сделать, т.к. Fashion-MNIST доступен как набор данных, который возвращается вызовом API к TensorFlow. Мы просто объявляем объект типа MNIST, загружая его из базы данных Keras, и если мы вызовем метод load_data у этого объекта, он вернет нам 4 списка. Это данные для обучения, метки для обучения, данные для тестирования и метки для тестирования. Вы можете спросить: для чего они все нужны? Итак, при создании подобной нейронной сети хорошей практикой будет использовать часть ваших данных для обучения нейронной сети, а аналогичные данные, которые модель еще не видела, использовать для проверки, насколько хорошо она распознает изображения. Таким образом, в наборе данных Fashion-MNIST 60,000 из 70,000 изображений используются для обучения сети, а остальные 10,000 изображений, которые сеть раньше не видела, могут использоваться для тестирования того, насколько хорошо или плохо она работает. И этот код как раз и даст вам такие наборы данных. Каждый набор содержит данные: сами изображения и метки, указывающие, что находится на этом изображении. Например, данные для обучения будут содержать изображения вроде этого, и метку, описывающую изображение, вроде этой. Если на этой картинке изображен ботинок, то его описанием будет метка с номером 9. Зачем, по-вашему, так делать? Для этого есть две основные причины. Во-первых, естественно, компьютеры работают с числами лучше, чем с текстом. Во-вторых, очень важно, что это может нам помочь снизить перекос*. [обыгрываются значения слова bias: систематическая ошибка, смещение оценки - прим.] Если бы мы пометили это как "ankle boot", мы бы, конечно, оказали предпочтение англоговорящим. Но если мы работаем с цифровой меткой, то мы сможем ссылаться на неё на нашем родном языке, будь то английский, китайский, японский, или даже ирландский, как здесь.

5(w2) The structure of Fashion MNIST data (15.MLg_1c)

(Структура данных Fashion MNIST)
Here you saw how the data can be loaded into Python data structures that make it easy to train a neural network. You saw how the image is represented as a 28x28 array of greyscales, and how its label is a number. Using a number is a first step in avoiding bias -- instead of labelling it with words in a specific language and excluding people who don’t speak that language! You can learn more about bias and techniques to avoid it here.
---------------------------------------------------------------
Здесь вы увидели, как данные можно загружать в структуры данных Python, которые упрощают обучение нейронной сети. Вы видели, как изображение представлено в виде массива оттенков серого 28x28, а его метка представляет собой число. Использование числа — это первый шаг к тому, чтобы избежать предвзятости — вместо того, чтобы обозначать его словами на определенном языке и исключать людей, которые не говорят на этом языке! Вы можете узнать больше о предвзятости и способах ее избежать здесь.

6(w2)-video4: (15.MLg_1c)

Okay. So now we will look at the code for the neural network definition. Remember last time we had a sequential with just one layer in it. Now we have three layers. The important things to look at are the first and the last layers. The last layer has 10 neurons in it because we have ten classes of clothing in the dataset. They should always match. The first layer is a flatten layer with the input shaping 28 by 28. Now, if you remember our images are 28 by 28, so we're specifying that this is the shape that we should expect the data to be in. Flatten takes this 28 by 28 square and turns it into a simple linear array. The interesting stuff happens in the middle layer, sometimes also called a hidden layer. This is a 128 neurons in it, and I'd like you to think about these as variables in a function. Maybe call them x1, x2 x3, etc. Now, there exists a rule that incorporates all of these that turns the 784 values of an ankle boot into the value nine, and similar for all of the other 70,000. It's too complex a function for you to see by mapping the images yourself, but that's what a neural net does. So, for example, if you then say the function was y equals w1 times x1, plus w2 times x2, plus w3 times x3, all the way up to a w128 times x128. By figuring out the values of w, then y will be nine, when you have the input value of the shoe. You'll see that it's doing something very, very similar to what we did earlier when we figured out y equals 2x minus one. In that case the two, was the weight of x. So, I'm saying y equals w1 times x1, etc. Now, don't worry if this isn't very clear right now. Over time, you will get the hang of it, seeing that it works, and there's also some tools that will allow you to peek inside to see what's going on. The important thing for now is to get the code working, so you can see a classification scenario for yourself. You can also tune the neural network by adding, removing and changing layer size to see the impact. You'll do that in the next exercise. Also, if you want to go further, checkout this tutorial from Andrew on YouTube, which will clarify how dense connected layer's work from the theoretical and mathematical perspective. But for now, let's get back to the code.
---------------------------------------------------------------
Итак, теперь мы посмотрим код определяющий нейронную сеть. Напомню, в прошлый раз у нас была последовательность лишь одним лишь слоем. Теперь у нас 3 слоя. Достойными внимания являются первый и последний слои. Последний слой состоит из 10 нейронов, т.к. у нас десять классов одежды в наборе данных. Выход и число классов всегда должны совпадать. Первый слой является развёрнутым (Flatten), принимая на вход матрицу размерностью 28х28. Если вы помните, размер наших изображений 28х28. Таким образом, мы этим определяем размерность данных, которые мы ожидаем на входе. Процедура развёртывания берёт эту матрицу 28х28 и превращает её в простой линейный список. Интересные вещи происходят в промежуточном слое, который иногда называют также скрытым слоем. Он состоит из 128 нейронов, и я бы хотел, чтобы вы рассматривали их как переменные некоторой функции. Назовём их x1, x2 x 3, и т.д. И существует правило, которое включает их все в себя, и превращает 784 цифры, изображающие ботинок, — в цифру 9. И то же самое для остальных 70,000 изображений. Эта функция слишком сложна, чтобы вы ее увидели сами, сопоставляя изображения, но это именно то, что делает нейронная сеть. Например, если бы функция, скажем, была y = w1*x1 + y = w1*x1 + w2*x2 + y = w1*x1 + w2*x2 + w3*x3 + ... и так далее, до w128*x128. Определив значения w, мы будем получать Y = 9 всякий раз, когда мы подаём на вход изображение обуви. Вы увидите, что происходит что-то очень похожее на то, что мы делали ранее, когда определяли Y = 2*X - 1. В том случае 2 было весовым коэффициентом для X. Таким образом, мы говорим, что y = w1*x1, и т.д. Не волнуйтесь, если сейчас это не совсем понятно. Со временем вы поймёте это, наблюдая за тем, как это работает. Также есть инструменты, которые позволят вам заглянуть внутрь и увидеть, что происходит. Сейчас важно иметь рабочий код, чтобы вы могли сами увидеть, как работает классификатор. Вы также можете настраивать нейронную сеть, добавляя и удаляя слои, или изменяя их размерность, чтобы увидеть, как это влияет на результат. Вы займётесь этим в следующем упражнении. Также, если вы хотите узнать больше, обратите внимание на этот курс от Эндрю на YouTube, который прольёт свет на то, как работают полносвязные слои с теоретической и математической точки зрения. А пока давайте вернемся к коду.
DeepLearningAI
Neural Network Overview (C1W3L01)
https://www.youtube.com/watch?v=fXOsFF95ifk

=======

16(w1) Week 1 Resources (15.MLg_1c)

That brings you to the end of what you need to look at for Week 1. If you’re eager to learn more, before we go to Week 2, there are some great resources you can check out:
(Это подводит вас к концу того, что вам нужно изучить в течение недели 1. Если вы хотите узнать больше, прежде чем мы перейдем к неделе 2, есть несколько отличных ресурсов, которые вы можете проверить:)
----------------------------------------------------------------------------------------------
- AI For Everyone is a non-technical course that will help you understand many of the AI technologies we will discuss later in this course, and help you spot opportunities in applying this technology to solve your problems.
https://www.deeplearning.ai/ai-for-everyone/
- TensorFlow is available at TensorFlow.org, and video updates from the TensorFlow team are at youtube.com/tensorflow
(ИИ для всех — это нетехнический курс, который поможет вам понять многие технологии ИИ, которые мы обсудим позже в этом курсе, и поможет вам определить возможности применения этой технологии для решения ваших проблем.
https://www.deeplearning.ai/ai-for-everyone/
TensorFlow доступен на TensorFlow.org, а видеообновления от команды TensorFlow — на youtube.com/tensorflow.)
----------------------------------------------------------------------------------------------
Play with a neural network right in the browser at http://playground.tensorflow.org. See if you can figure out the parameters to get the neural network to pattern match to the desired groups. The spiral is particularly challenging!
(Играйте с нейронной сетью прямо в браузере на http://playground.tensorflow.org. Посмотрите, сможете ли вы определить параметры, чтобы заставить нейронную сеть сопоставлять шаблоны с нужными группами. Спираль особенно сложна!)

NEXT week_2 (15.MLg_1c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2) Introduction to Computer Vision (15.MLg_1c)

(Введение в компьютерное зрение)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 15 minutes
Self-study: 1,46 hour
Graded tasks (Tasks to be assessed): 2

(w2) Introduction: (15.MLg_1c)

Welcome to week 2 of the course! In week 1 you learned all about how Machine Learning and Deep Learning is a new programming paradigm. This week you’re going to take that to the next level by beginning to solve problems of computer vision with just a few lines of code! Check out this conversation between Laurence and Andrew where they discuss it and introduce you to Computer Vision!
---------------------------------------------------------------
Добро пожаловать на вторую неделю курса! На первой неделе вы узнали все о том, что машинное обучение и глубокое обучение — это новая парадигма программирования. На этой неделе вы перейдете на следующий уровень, начав решать проблемы компьютерного зрения всего несколькими строками кода! Посмотрите этот разговор между Лоуренсом и Эндрю, где они обсуждают это и знакомят вас с Computer Vision!

(w2) Learning Objectives: (15.MLg_1c)

● Use callback functions for tracking model loss and accuracy during training
● Make predictions on how the layer size affects network predictions and training speed
● Implement pixel value normalization to speed up network training
● Build a multilayer neural network for classifying the Fashion MNIST image dataset
---------------------------------------------------------------
● Используйте функции обратного вызова для отслеживания потерь и точности модели во время обучения.
● Делайте прогнозы о том, как размер слоя влияет на прогнозы сети и скорость обучения.
● Реализуйте нормализацию значений пикселей, чтобы ускорить обучение сети.
● Создайте многослойную нейронную сеть для классификации набора данных изображений Fashion MNIST.

1(w2)-video1: (15.MLg_1c)

So in that lesson, we just saw the basics of the new programming paradigm that comes with machine learning and deep learning, and how instead of like expressing rules in a programming language, we can start getting data and using labeled data to open up new scenarios like activity recognition. Then for a little bit of fun, we actually started doing our first piece of code. We built a super simple neural network that fit data like an x and y data onto a line but that was just "Hello, World". Right, Andrew? So fitting straight lines seems like the "Hello, world" most basic implementation learning algorithm. But one of the most amazing things about machine learning is that, that core of the idea of fitting the x and y relationship is what lets us do amazing things like, have computers look at the picture and do activity recognition, or look at the picture and tell us, is this a dress, or a pair of pants, or a pair of shoes really hard for humans, and amazing that computers can now use this to do these things as well. Right, like computer vision is a really hard problem to solve, right? Because you're saying like dress or shoes. It's like how would I write rules for that? How would I say, if this pixel then it's a shoe, if that pixel then its a dress. It's really hard to do, so the labeled samples are the right way to go. Yeah. One of the non-intuitive things about vision is that it's so easy for a person to look at you and say, you're wearing a shirt, it's so hard for a computer to figure it out. Because it's so easy for humans to recognize objects, it's almost difficult to understand why this is a complicated thing for a computer to do. What the computer has to do is look at all numbers, all the pixel brightness value, saying look at all of these numbers saying, these numbers correspond to a black shirt, and it's amazing that with machine and deep learning computers are getting really good at this. Right, so it's like with the code that we just used in the previous lesson as you mentioned, it provides a template for everything that we can do with deep learning by designing a Neural network in the layers to be able to recognize patterns like this. So maybe we can do that with clothes recognition today. What do you think? Yeah. So in the next video, you'll learn how to write code to take this paradigm you've already saw in a previous video, but to now apply it to recognizing clothes from labeled data. Please go on to the next video.
---------------------------------------------------------------
В прошлом уроке мы рассмотрели основы новой парадигмы программирования, вытекающей из машинного обучения и глубокого обучения, и увидели, как вместо выражения правил на языке программирования — мы можем начать собирать данные и использовать размеченные данные, что открывает новые сценарии, такие как распознавание действий. Затем, чтобы немного развлечься, мы начали писать наш первый фрагмент кода. Мы создали очень простую нейронную сеть, подгоняющую наши данные, X и Y под прямую линию, но это было лишь "Hello, World". Правильно, Эндрю? Да, подгонка под прямые линии — что-то вроде "Hello, World", самая простая реализация алгоритма обучения. Но одна из наиболее удивительных вещей в машинном обучении состоит в том, что сама идея подгонки взаимосвязи между X и Y позволяет нам делать удивительные вещи, например, заставить компьютер взять картинку и распознавать действия, изображенные на ней. Или смотреть на картинку и говорить нам, изображено ли здесь платье, или пара брюк, или пара обуви — и это тяжело для людей, и замечательно, что компьютеры могут сейчас, используя это, также делать эти вещи. Верно, например, компьютерное зрение — действительно трудная в решении задача, так? Потому что вы говорите, платье или обувь. А как бы я написал правила для этого? Как мне это сказать: если вот такой пиксел, тогда это обувь, а если вот такой, то это одежда? Это очень трудно сделать, поэтому размеченные образцы — это верное направление. Да. Одна из неочевидных вещей в компьютерном зрении — это то, что для человека очень просто взглянуть на вас и сказать: "на вас одета футболка", а для компьютера очень сложно определить это. И поскольку человеку так легко распознать объекты, то сложно понять, почему это же это так сложно сделать компьютеру. Компьютер вынужден изучать все числа, яркости всех пикселов, и глядя на все эти цифры, сказать: "эти числа соответствуют черной футболке". И удивительно, что с помощью машинного и глубокого обучения компьютеры довольно хорошо с этим справляются. Верно, это что-то наподобие кода, который мы недавно использовали, в предыдущем уроке. Как вы упоминали он предоставляет заготовку для всего, что мы можем делать с помощью глубокого обучения, проектируя слои нейронной сети, чтобы иметь возможность распознавать образы, как этот. Так что, возможно, сегодня мы сможем это сделать для распознавания одежды. Как вы думаете? Да. Поэтому в следующем видео вы научитесь тому, как писать код, применяя ту же парадигму, которую вы уже видели в предыдущем видео, но сейчас применить ее к распознаванию одежды по размеченным данным. Приглашаем вас перейти к следующему видео.

2(w2)-video2: (15.MLg_1c)

In the previous lesson, you learned what the machine learning paradigm is and how you use data and labels and have a computer in fair the rules between them for you. You looked at a very simple example where it figured out the relationship between two sets of numbers. Let's now take this to the next level by solving a real problem, computer vision. Computer vision is the field of having a computer understand and label what is present in an image. Consider this slide. When you look at it, you can interpret what a shirt is or what a shoe is, but how would you program for that? If an extra terrestrial who had never seen clothing walked into the room with you, how would you explain the shoes to him? It's really difficult, if not impossible to do right? And it's the same problem with computer vision. So one way to solve that is to use lots of pictures of clothing and tell the computer what that's a picture of and then have the computer figure out the patterns that give you the difference between a shoe, and a shirt, and a handbag, and a coat. That's what you're going to learn how to do in this section. Fortunately, there's a data set called Fashion MNIST which gives a 70 thousand images spread across 10 different items of clothing. These images have been scaled down to 28 by 28 pixels. Now usually, the smaller the better because the computer has less processing to do. But of course, you need to retain enough information to be sure that the features and the object can still be distinguished. If you look at this slide you can still tell the difference between shirts, shoes, and handbags. So this size does seem to be ideal, and it makes it great for training a neural network. The images are also in gray scale, so the amount of information is also reduced. Each pixel can be represented in values from zero to 255 and so it's only one byte per pixel. With 28 by 28 pixels in an image, only 784 bytes are needed to store the entire image. Despite that, we can still see what's in the image and in this case, it's an ankle boot, right?
---------------------------------------------------------------
В предыдущем уроке вы узнали, что представляет из себя парадигма машинного обучения? и как использовать данные и метки, как заставить компьютер вывести за вас связывающие их правила. Вы увидели очень простой пример, где выявлялась взаимосвязь между двумя наборами чисел. Давайте теперь выведем это на следующий уровень, решая реальную задачу компьютерного зрения. Компьютерное зрение — это область, где компьютер понимает и отмечает то, что присутствует на картинке. Рассмотрим этот слайд. Когда вы смотрите на него, вы можете распознать, где рубашка, где обувь, — но как бы вы это запрограммировали? Если вместе с вами в комнате оказался пришелец, который никогда не видел верхнюю одежду, то какое бы вы ему дали описание обуви? Это действительно трудно сделать, если вообще возможно, верно? И та же самая проблема стоит перед компьютерным зрением. Одним из способов решить ее — использовать множество картинок одежды, и сказать компьютеру, что на каком изображении, а затем дать компьютеру выявить шаблоны, позволяющие различать обувь, рубашку, сумочку и пальто. Как это сделать, вы и узнаете в данном разделе. К счастью, у нас есть набор данных под названием Fashion MNIST, в котором содержится 70 тысяч изображений, охватывающих 10 различных предметов одежды. Эти изображения уменьшены до размера 28х28 пикселей. Как правило, чем меньше — тем лучше, потому что компьютеру придётся выполнять меньше вычислений. Но, конечно, вам нужно сохранить достаточно информации, чтобы гарантировать, что признаки объектов по-прежнему различимы. Если вы взглянете на этот слайд, то все еще можете провести различие между футболками, обувью и сумочками. Так что этот размер выглядит идеальным, и это делает его отлично подходящим для обучения нейронной сети. Кроме того, изображения полутоновые, то есть, количество информации здесь также снижается. Каждый пиксел может быть представлен значениями от 0 до 255, то есть, всего один байт на пиксел. Для изображения 28 на 28 пикселов нам необходимо всего 784 байта, чтобы сохранить все изображение. Несмотря на это, нам все еще видно, что изображено на картинке — и в данном случае, это ботинок, верно?

3(w2) Exploring how to use data: (15.MLg_1c)

(Изучение того, как использовать данные)
Machine Learning depends on having good data to train a system with. In the previous video, you were given a scenario to train a system to recognize fashion images. The data comes from a dataset called Fashion MNIST, and you can learn more about it on GitHub
here. In the next video, you’ll see how to load that data and prepare it for training.
https://github.com/zalandoresearch/fashion-mnist
---------------------------------------------------------------
Машинное обучение зависит от наличия хороших данных для обучения системы. В предыдущем видео вам дали сценарий обучения системы распознаванию фэшн-изображений. Данные поступают из набора данных под названием Fashion MNIST, и вы можете узнать больше о нем на GitHub.
здесь. В следующем видео вы увидите, как загрузить эти данные и подготовить их к обучению.

4(w2)-video3: (15.MLg_1c)

So what will handling this look like in code? In the previous lesson, you learned about TensorFlow and Keras, and how to define a super simple neural network with them. In this lesson, you're going to use them to go a little deeper but the overall API should look familiar. The one big difference will be in the data. The last time you had your six pairs of numbers, so you could hard code it. This time you have to load 70,000 images off the disk, so there'll be a bit of code to handle that. Fortunately, it's still quite simple because Fashion-MNIST is available as a data set with an API call in TensorFlow. We simply declare an object of type MNIST loading it from the Keras database. On this object, if we call the load data method, it will return four lists to us. That's the training data, the training labels, the testing data, and the testing labels. Now, what are these you might ask? Well, when building a neural network like this, it's a nice strategy to use some of your data to train the neural network and similar data that the model hasn't yet seen to test how good it is at recognizing the images. So in the Fashion-MNIST data set, 60,000 of the 70,000 images are used to train the network, and then 10,000 images, one that it hasn't previously seen, can be used to test just how good or how bad it is performing. So this code will give you those sets. Then, each set has data, the images themselves and labels and that's what the image is actually of. So for example, the training data will contain images like this one, and a label that describes the image like this. While this image is an ankle boot, the label describing it is the number nine. Now, why do you think that might be? There's two main reasons. First, of course, is that computers do better with numbers than they do with texts. Second, importantly, is that this is something that can help us reduce bias. If we labeled it as an ankle boot, we would be of course biasing towards English speakers. But with it being a numeric label, we can then refer to it in our appropriate language be it English, Chinese, Japanese, or here, even Irish Gaelic.
---------------------------------------------------------------
Итак, как же будет выглядеть эта обработка в коде? В предыдущем уроке вы узнали о TensorFlow и Keras, и как собрать сверхпростую нейронную сеть с их помощью. В этом уроке мы немного углубимся, но общий API будет быть вам знаком. Единственная большая разница будет в данных. В прошлый раз у вас было шесть пар чисел, поэтому их можно было захардкодить. На этот раз вам нужно будет загрузить 70,000 изображений с диска, поэтому здесь будет немного кода, который этим займется. К счастью, это все еще довольно просто сделать, т.к. Fashion-MNIST доступен как набор данных, который возвращается вызовом API к TensorFlow. Мы просто объявляем объект типа MNIST, загружая его из базы данных Keras, и если мы вызовем метод load_data у этого объекта, он вернет нам 4 списка. Это данные для обучения, метки для обучения, данные для тестирования и метки для тестирования. Вы можете спросить: для чего они все нужны? Итак, при создании подобной нейронной сети хорошей практикой будет использовать часть ваших данных для обучения нейронной сети, а аналогичные данные, которые модель еще не видела, использовать для проверки, насколько хорошо она распознает изображения. Таким образом, в наборе данных Fashion-MNIST 60,000 из 70,000 изображений используются для обучения сети, а остальные 10,000 изображений, которые сеть раньше не видела, могут использоваться для тестирования того, насколько хорошо или плохо она работает. И этот код как раз и даст вам такие наборы данных. Каждый набор содержит данные: сами изображения и метки, указывающие, что находится на этом изображении. Например, данные для обучения будут содержать изображения вроде этого, и метку, описывающую изображение, вроде этой. Если на этой картинке изображен ботинок, то его описанием будет метка с номером 9. Зачем, по-вашему, так делать? Для этого есть две основные причины. Во-первых, естественно, компьютеры работают с числами лучше, чем с текстом. Во-вторых, очень важно, что это может нам помочь снизить перекос*. [обыгрываются значения слова bias: систематическая ошибка, смещение оценки - прим.] Если бы мы пометили это как "ankle boot", мы бы, конечно, оказали предпочтение англоговорящим. Но если мы работаем с цифровой меткой, то мы сможем ссылаться на неё на нашем родном языке, будь то английский, китайский, японский, или даже ирландский, как здесь.

5(w2) The structure of Fashion MNIST data (15.MLg_1c)

(Структура данных Fashion MNIST)
Here you saw how the data can be loaded into Python data structures that make it easy to train a neural network. You saw how the image is represented as a 28x28 array of greyscales, and how its label is a number. Using a number is a first step in avoiding bias -- instead of labelling it with words in a specific language and excluding people who don’t speak that language! You can learn more about bias and techniques to avoid it here.
---------------------------------------------------------------
Здесь вы увидели, как данные можно загружать в структуры данных Python, которые упрощают обучение нейронной сети. Вы видели, как изображение представлено в виде массива оттенков серого 28x28, а его метка представляет собой число. Использование числа — это первый шаг к тому, чтобы избежать предвзятости — вместо того, чтобы обозначать его словами на определенном языке и исключать людей, которые не говорят на этом языке! Вы можете узнать больше о предвзятости и способах ее избежать здесь.

6(w2)-video4: (15.MLg_1c)

Okay. So now we will look at the code for the neural network definition. Remember last time we had a sequential with just one layer in it. Now we have three layers. The important things to look at are the first and the last layers. The last layer has 10 neurons in it because we have ten classes of clothing in the dataset. They should always match. The first layer is a flatten layer with the input shaping 28 by 28. Now, if you remember our images are 28 by 28, so we're specifying that this is the shape that we should expect the data to be in. Flatten takes this 28 by 28 square and turns it into a simple linear array. The interesting stuff happens in the middle layer, sometimes also called a hidden layer. This is a 128 neurons in it, and I'd like you to think about these as variables in a function. Maybe call them x1, x2 x3, etc. Now, there exists a rule that incorporates all of these that turns the 784 values of an ankle boot into the value nine, and similar for all of the other 70,000. It's too complex a function for you to see by mapping the images yourself, but that's what a neural net does. So, for example, if you then say the function was y equals w1 times x1, plus w2 times x2, plus w3 times x3, all the way up to a w128 times x128. By figuring out the values of w, then y will be nine, when you have the input value of the shoe. You'll see that it's doing something very, very similar to what we did earlier when we figured out y equals 2x minus one. In that case the two, was the weight of x. So, I'm saying y equals w1 times x1, etc. Now, don't worry if this isn't very clear right now. Over time, you will get the hang of it, seeing that it works, and there's also some tools that will allow you to peek inside to see what's going on. The important thing for now is to get the code working, so you can see a classification scenario for yourself. You can also tune the neural network by adding, removing and changing layer size to see the impact. You'll do that in the next exercise. Also, if you want to go further, checkout this tutorial from Andrew on YouTube, which will clarify how dense connected layer's work from the theoretical and mathematical perspective. But for now, let's get back to the code.
---------------------------------------------------------------
Итак, теперь мы посмотрим код определяющий нейронную сеть. Напомню, в прошлый раз у нас была последовательность лишь одним лишь слоем. Теперь у нас 3 слоя. Достойными внимания являются первый и последний слои. Последний слой состоит из 10 нейронов, т.к. у нас десять классов одежды в наборе данных. Выход и число классов всегда должны совпадать. Первый слой является развёрнутым (Flatten), принимая на вход матрицу размерностью 28х28. Если вы помните, размер наших изображений 28х28. Таким образом, мы этим определяем размерность данных, которые мы ожидаем на входе. Процедура развёртывания берёт эту матрицу 28х28 и превращает её в простой линейный список. Интересные вещи происходят в промежуточном слое, который иногда называют также скрытым слоем. Он состоит из 128 нейронов, и я бы хотел, чтобы вы рассматривали их как переменные некоторой функции. Назовём их x1, x2 x 3, и т.д. И существует правило, которое включает их все в себя, и превращает 784 цифры, изображающие ботинок, — в цифру 9. И то же самое для остальных 70,000 изображений. Эта функция слишком сложна, чтобы вы ее увидели сами, сопоставляя изображения, но это именно то, что делает нейронная сеть. Например, если бы функция, скажем, была y = w1*x1 + y = w1*x1 + w2*x2 + y = w1*x1 + w2*x2 + w3*x3 + ... и так далее, до w128*x128. Определив значения w, мы будем получать Y = 9 всякий раз, когда мы подаём на вход изображение обуви. Вы увидите, что происходит что-то очень похожее на то, что мы делали ранее, когда определяли Y = 2*X - 1. В том случае 2 было весовым коэффициентом для X. Таким образом, мы говорим, что y = w1*x1, и т.д. Не волнуйтесь, если сейчас это не совсем понятно. Со временем вы поймёте это, наблюдая за тем, как это работает. Также есть инструменты, которые позволят вам заглянуть внутрь и увидеть, что происходит. Сейчас важно иметь рабочий код, чтобы вы могли сами увидеть, как работает классификатор. Вы также можете настраивать нейронную сеть, добавляя и удаляя слои, или изменяя их размерность, чтобы увидеть, как это влияет на результат. Вы займётесь этим в следующем упражнении. Также, если вы хотите узнать больше, обратите внимание на этот курс от Эндрю на YouTube, который прольёт свет на то, как работают полносвязные слои с теоретической и математической точки зрения. А пока давайте вернемся к коду.
DeepLearningAI
Neural Network Overview (C1W3L01)
https://www.youtube.com/watch?v=fXOsFF95ifk

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
import tensorflow as tf
from tensorflow import keras

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

7(w2)-See how it's done (15.MLg_1c)

(Посмотрите, как это делается)
In the next video, Laurence will step you through a workbook where you can see a neural network being trained on Fashion images. After that you’ll be able to try the workbook for yourself!
---------------------------------------------------------------
В следующем видео Лоуренс проведет вас через рабочую тетрадь, где вы увидите, как нейронная сеть обучается на изображениях моды. После этого вы сможете попробовать книгу самостоятельно!

8(w2)-video5: Walk through a Notebook for computer vision (15.MLg_1c)

(Прогулка по ноутбуку для компьютерного зрения)
Okay. So you just saw how to create a neural network that gives basic computer vision capabilities to recognize different items of clothing. Let's now work through a workbook that has all of the code to do that. You'll then go through this workbook yourself and if you want you can try some exercises. Let's start by importing TensorFlow. I'm going to get the fashion MNIST data using tf.kares.datasets. By calling the load data method, I get training data and labels as well as test data and labels. For more details on these, check back to the previous video. The data for a particular image is a grid of values from zero to 255 with pixel grayscale values. Using matplotlib, I can plot these as an image to make it easier to inspect. I can also print out the raw values so we can see what they look like. Here you can see the raw values for the pixel numbers from zero to 255, and here you can see the actual image. That was for the first image in the array. Let's take a look at the image at index 42 instead, and we can see the different pixel values and the actual graphic. *long pause* Our image has values from zero to 255, but neural networks work better with normalized data. So, let's change it to between zero and one simply by dividing every value by 255. In Python, you can actually divide an entire array with one line of code like this. So now we design our model. As explained earlier, there's an input layer in the shape of the data and an output layer in the shape of the classes, and one hidden layer that tries to figure out the roles between them. Now we compile the model to finding the loss function and the optimizer, and the goal of these is as before, to make a guess as to what the relationship is between the input data and the output data, measure how well or how badly it did using the loss function, use the optimizer to generate a new guess and repeat. We can then try to fit the training images to the training labels. We'll just do it for five epochs to be quick. We spend about 25 seconds training it over five epochs and we end up with a loss of about 0.29. That means it's pretty accurate in guessing the relationship between the images and their labels. That's not great, but considering it was done in just 25 seconds with a very basic neural network, it's not bad either. But a better measure of performance can be seen by trying the test data. These are images that the network has not yet seen. You would expect performance to be worse, but if it's much worse, you have a problem. As you can see, it's about 0.345 loss, meaning it's a little bit less accurate on the test set. It's not great either, but we know we're doing something right. Your job now is to go through the workbook, try the exercises and see by tweaking the parameters on the neural network or changing the epochs, if there's a way for you to get it above 0.71 loss accuracy on training data and 0.66 accuracy on test data. Give it a try for yourself.
---------------------------------------------------------------
Итак, вы уже видели как создавать нейронную сеть, которая обладает базовыми возможностями компьютерного зрения, чтобы распознавать различные предметы одежды. Давайте теперь проработаем workbook, который содержит весь необходимый для этого код. Позже вы сможете поработать с ним самостоятельно, и если захотите, сможете попробовать сделать несколько упражнений. Давайте начнём с импорта TensorFlow. Для начала я получу данные Fashion MNIST, используя tf.keras.datasets. Вызывая метод load_data, я получаю данные и метки для обучения сети, а также тестовые данные и метки. Для более подробной информации об этом просмотрите предыдущее видео. Данные конкретного изображения — это матрица значений яркости в шкале серого от 0 до 255. С помощью matplotlib я могу вывести их в виде изображения, чтобы было проще их изучать. Я также могу вывести сырые данные, чтобы посмотреть, на что они похожи. Здесь мы можем увидеть исходные значения яркостей пикселов от 0 до 255, а вот здесь можно увидеть само изображение. Всё это — для первого изображения в массиве. Давайте теперь посмотрим на изображение с номером 42, и мы увидим другие значения яркостей пикселов, и само изображение. Наше изображение содержит значения от 0 до 255, однако нейронная сеть лучше работает с нормализованными данными. Поэтому давайте приведем значения яркостей к диапазону от 0 до 1, просто поделив каждое значение на 255. На языке Python вы можете разделить весь массив в одну строку кода, как здесь. Теперь разработаем нашу модель. Как объяснялось ранее, должен быть входной слой, соответствующий размерности данных, и выходной слой, соответствующий количеству распознаваемых классов, и один один скрытый слой, который пытается вывести правила соответствия между ними. Теперь мы компилируем модель, используя выбранные функцию потерь и оптимизатор, и цель этого всего, как и раньше — сделать предположение о том, какова взаимосвязь между входными и выходными данными, измерить с помощью функции потерь, насколько хорошо или насколько плохо оно было сделано, сгенерировать новое предположение, используя оптимизатор, — и всё повторить. После этого мы можем попробовать сопоставить обучающие изображения и их метки. Мы это сделаем всего за 5 эпох, чтобы было быстрее. Мы потратили около 25 секунд, обучая сеть в течение 5 эпох, и закончили с ошибкой в районе 0.29. Это означает, что модель довольно точна в определении взаимосвязи между изображениями и их метками. Это не так круто, конечно, но с учётом того, что это было сделано всего за 25 секунд и с использованием очень простой нейронной сети — то это не так уж и плохо. Но лучшую оценку работы сети мы сможем получить, используя тестовые данные. Это изображения, которых сеть еще не видела. Стоит ожидать, что результаты сети будут хуже, но если они сильно хуже — то у вас есть проблема. Как вы видите, ошибка в районе 0.345, то есть, сеть немного менее точна на тестовых данных. Тоже не так круто, как хотелось бы, но мы знаем, что мы на правильном пути. Теперь ваша задача состоит в том, чтобы пройти по всему workbook, попробовать сделать упражнения, и узнать, подкручивая параметры нейронной сети или изменяя количество эпох, — есть ли способ получить точность выше 0.71 на обучающих данных — и точность выше 0.66 на тестовых данных. Попытайтесь это сделать самостоятельно.

9(w2)-Get hands-on with computer vision (Lab 1) (15.MLg_1c)

( Познакомьтесь с компьютерным зрением (лабораторная работа 1) )
Now that you’ve seen the workbook, it’s time to try it for yourself. You can find it here. We’ve also provided a number of exercises you can try at the bottom of the workbook. These will help you poke around and experiment with the code, and will help you with the code you’ll need to write at the end of the week, so it’s really worth spending some time on them! I'd recommend you spend at least 1 hour playing with this workbook. It will be really worth your time!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W2/ungraded_labs/C1_W2_Lab_1_beyond_hello_world.ipynb
When you’re done with that, the next thing to do is to explore callbacks. One of the things you can do with that is to train a neural network until it reaches a threshold you want, and then stop training. You’ll see that in the next video.
---------------------------------------------------------------
Теперь, когда вы ознакомились с рабочей тетрадью, пришло время попробовать ее самостоятельно. Вы можете найти это здесь. Мы также предоставили ряд упражнений, которые вы можете выполнить в нижней части рабочей тетради. Они помогут вам копаться и экспериментировать с кодом, а также помогут вам с кодом, который вам нужно будет написать в конце недели, так что действительно стоит потратить на них некоторое время! Я бы порекомендовал вам потратить не менее 1 часа, играя с этой книгой. Это действительно стоит вашего времени!
Когда вы закончите с этим, следующее, что нужно сделать, это изучить обратные вызовы. Одна из вещей, которые вы можете сделать с этим, — обучать нейронную сеть, пока она не достигнет желаемого порога, а затем прекратить обучение. Вы увидите это в следующем видео.

# LOAD DATASET

=======

7(w2)-See how it's done (15.MLg_1c)

(Посмотрите, как это делается)
In the next video, Laurence will step you through a workbook where you can see a neural network being trained on Fashion images. After that you’ll be able to try the workbook for yourself!
---------------------------------------------------------------
В следующем видео Лоуренс проведет вас через рабочую тетрадь, где вы увидите, как нейронная сеть обучается на изображениях моды. После этого вы сможете попробовать книгу самостоятельно!

8(w2)-video5: Walk through a Notebook for computer vision (15.MLg_1c)

(Прогулка по ноутбуку для компьютерного зрения)
Okay. So you just saw how to create a neural network that gives basic computer vision capabilities to recognize different items of clothing. Let's now work through a workbook that has all of the code to do that. You'll then go through this workbook yourself and if you want you can try some exercises. Let's start by importing TensorFlow. I'm going to get the fashion MNIST data using tf.kares.datasets. By calling the load data method, I get training data and labels as well as test data and labels. For more details on these, check back to the previous video. The data for a particular image is a grid of values from zero to 255 with pixel grayscale values. Using matplotlib, I can plot these as an image to make it easier to inspect. I can also print out the raw values so we can see what they look like. Here you can see the raw values for the pixel numbers from zero to 255, and here you can see the actual image. That was for the first image in the array. Let's take a look at the image at index 42 instead, and we can see the different pixel values and the actual graphic. *long pause* Our image has values from zero to 255, but neural networks work better with normalized data. So, let's change it to between zero and one simply by dividing every value by 255. In Python, you can actually divide an entire array with one line of code like this. So now we design our model. As explained earlier, there's an input layer in the shape of the data and an output layer in the shape of the classes, and one hidden layer that tries to figure out the roles between them. Now we compile the model to finding the loss function and the optimizer, and the goal of these is as before, to make a guess as to what the relationship is between the input data and the output data, measure how well or how badly it did using the loss function, use the optimizer to generate a new guess and repeat. We can then try to fit the training images to the training labels. We'll just do it for five epochs to be quick. We spend about 25 seconds training it over five epochs and we end up with a loss of about 0.29. That means it's pretty accurate in guessing the relationship between the images and their labels. That's not great, but considering it was done in just 25 seconds with a very basic neural network, it's not bad either. But a better measure of performance can be seen by trying the test data. These are images that the network has not yet seen. You would expect performance to be worse, but if it's much worse, you have a problem. As you can see, it's about 0.345 loss, meaning it's a little bit less accurate on the test set. It's not great either, but we know we're doing something right. Your job now is to go through the workbook, try the exercises and see by tweaking the parameters on the neural network or changing the epochs, if there's a way for you to get it above 0.71 loss accuracy on training data and 0.66 accuracy on test data. Give it a try for yourself.
---------------------------------------------------------------
Итак, вы уже видели как создавать нейронную сеть, которая обладает базовыми возможностями компьютерного зрения, чтобы распознавать различные предметы одежды. Давайте теперь проработаем workbook, который содержит весь необходимый для этого код. Позже вы сможете поработать с ним самостоятельно, и если захотите, сможете попробовать сделать несколько упражнений. Давайте начнём с импорта TensorFlow. Для начала я получу данные Fashion MNIST, используя tf.keras.datasets. Вызывая метод load_data, я получаю данные и метки для обучения сети, а также тестовые данные и метки. Для более подробной информации об этом просмотрите предыдущее видео. Данные конкретного изображения — это матрица значений яркости в шкале серого от 0 до 255. С помощью matplotlib я могу вывести их в виде изображения, чтобы было проще их изучать. Я также могу вывести сырые данные, чтобы посмотреть, на что они похожи. Здесь мы можем увидеть исходные значения яркостей пикселов от 0 до 255, а вот здесь можно увидеть само изображение. Всё это — для первого изображения в массиве. Давайте теперь посмотрим на изображение с номером 42, и мы увидим другие значения яркостей пикселов, и само изображение. Наше изображение содержит значения от 0 до 255, однако нейронная сеть лучше работает с нормализованными данными. Поэтому давайте приведем значения яркостей к диапазону от 0 до 1, просто поделив каждое значение на 255. На языке Python вы можете разделить весь массив в одну строку кода, как здесь. Теперь разработаем нашу модель. Как объяснялось ранее, должен быть входной слой, соответствующий размерности данных, и выходной слой, соответствующий количеству распознаваемых классов, и один один скрытый слой, который пытается вывести правила соответствия между ними. Теперь мы компилируем модель, используя выбранные функцию потерь и оптимизатор, и цель этого всего, как и раньше — сделать предположение о том, какова взаимосвязь между входными и выходными данными, измерить с помощью функции потерь, насколько хорошо или насколько плохо оно было сделано, сгенерировать новое предположение, используя оптимизатор, — и всё повторить. После этого мы можем попробовать сопоставить обучающие изображения и их метки. Мы это сделаем всего за 5 эпох, чтобы было быстрее. Мы потратили около 25 секунд, обучая сеть в течение 5 эпох, и закончили с ошибкой в районе 0.29. Это означает, что модель довольно точна в определении взаимосвязи между изображениями и их метками. Это не так круто, конечно, но с учётом того, что это было сделано всего за 25 секунд и с использованием очень простой нейронной сети — то это не так уж и плохо. Но лучшую оценку работы сети мы сможем получить, используя тестовые данные. Это изображения, которых сеть еще не видела. Стоит ожидать, что результаты сети будут хуже, но если они сильно хуже — то у вас есть проблема. Как вы видите, ошибка в районе 0.345, то есть, сеть немного менее точна на тестовых данных. Тоже не так круто, как хотелось бы, но мы знаем, что мы на правильном пути. Теперь ваша задача состоит в том, чтобы пройти по всему workbook, попробовать сделать упражнения, и узнать, подкручивая параметры нейронной сети или изменяя количество эпох, — есть ли способ получить точность выше 0.71 на обучающих данных — и точность выше 0.66 на тестовых данных. Попытайтесь это сделать самостоятельно.

9(w2)-Get hands-on with computer vision (Lab 1) (15.MLg_1c)

( Познакомьтесь с компьютерным зрением (лабораторная работа 1) )
Now that you’ve seen the workbook, it’s time to try it for yourself. You can find it here. We’ve also provided a number of exercises you can try at the bottom of the workbook. These will help you poke around and experiment with the code, and will help you with the code you’ll need to write at the end of the week, so it’s really worth spending some time on them! I'd recommend you spend at least 1 hour playing with this workbook. It will be really worth your time!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W2/ungraded_labs/C1_W2_Lab_1_beyond_hello_world.ipynb
When you’re done with that, the next thing to do is to explore callbacks. One of the things you can do with that is to train a neural network until it reaches a threshold you want, and then stop training. You’ll see that in the next video.
---------------------------------------------------------------
Теперь, когда вы ознакомились с рабочей тетрадью, пришло время попробовать ее самостоятельно. Вы можете найти это здесь. Мы также предоставили ряд упражнений, которые вы можете выполнить в нижней части рабочей тетради. Они помогут вам копаться и экспериментировать с кодом, а также помогут вам с кодом, который вам нужно будет написать в конце недели, так что действительно стоит потратить на них некоторое время! Я бы порекомендовал вам потратить не менее 1 часа, играя с этой книгой. Это действительно стоит вашего времени!
Когда вы закончите с этим, следующее, что нужно сделать, это изучить обратные вызовы. Одна из вещей, которые вы можете сделать с этим, — обучать нейронную сеть, пока она не достигнет желаемого порога, а затем прекратить обучение. Вы увидите это в следующем видео.

# LOAD DATASET

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# ------------------------
# LOAD DATASET
# ------------------------
import tensorflow as tf
# print(tf.__version__)

# Load the Fashion MNIST dataset
fmnist = tf.keras.datasets.fashion_mnist
# Load the training and split of the Fashion MNIST dataset
(training_images, training_labels), (test_images, test_labels) = fmnist.load_data()

# ------------------------
# vISUALISATE DATA
# ------------------------
import numpy as np
import matplotlib.pyplot as plt

# You can put between 0 to 59999 here
# index = 0
index = 42
# Set number of characters per row when printing
np.set_printoptions(linewidth=320)
# Print the label and image
print(f'LABEL: {training_labels[index]}')
print(f'\nIMAGE PIXEL ARRAY:\n {training_images[index]}')
# Visualize the image
plt.imshow(training_images[index], cmap='Greys')


   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# ------------------------
# CREATE MODEL
# ------------------------
# Normalize the pixel vlues of the train and test images
training_images = training_images / 255
test_images = test_images / 255

# Build the classification model
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
                                    tf.keras.layers.Dense(128, activation=tf.nn.relu),
                                    tf.keras.layers.Dense(10,activation=tf.nn.softmax)])

# ------------------------
# HOW WORKS SOFTMAX
# ------------------------
# Softmax берет список значений и масштабирует их так, чтобы сумма всех элементов была равна 1. 
# Применительно к выходным данным модели вы можете думать о масштабированных значениях как о вероятности 
# для этого класса. Например, в вашей модели классификации, которая имеет 10 единиц в выходном плотном слое,
#  самое высокое значение при индексе = 4 означает, что модель наиболее уверена в том, что входное
#   изображение одежды является пальто. Если он имеет индекс = 5, то это сандалии и так далее. 
#   См. приведенный ниже блок сокращенного кода, демонстрирующий эти концепции. Вы также можете 
#   посмотреть эту лекцию, если хотите узнать больше о функции Softmax и о том, как вычисляются значения.

# Declare sample imputs and convert to a tensor
inputs = np.array([[1.0, 3.0, 4.0, 2.0]])
inputs = tf.convert_to_tensor(inputs)
print(f'input to softmax function: {inputs.numpy()}')

# Feed the inputs to a softmax activation function
outputs = tf.keras.activations.softmax(inputs)
print(f'output of softmax functiion: {outputs.numpy()}')

# Get the sum of all values after the softmax
sum = tf.reduce_sum(outputs)
print(f'sum of outputs: {sum}')

# Get the index with highest value
prediction = np.argmax(outputs)
print(f'class with highest probability: {prediction}')
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
model.compile(optimizer = tf.optimizers.Adam(),
              loss = 'sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Evaluate the model on unseen data
model.evaluate(test_images, test_labels)

# ++++++++++++++++++++++++++++++++++++
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if(logs.get('accuracy') >= 0.6): # Experiment with changing this value
      print("\nReached 60% accuracy so cancelling training!")
      self.model.stop_training = True

callbacks = myCallback()
model.fit(training_images, training_labels, epochs=5, callbacks=[callbacks])
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

10(w2)-video6: Using Callbacks to control training (15.MLg_1c)

(Использование обратных вызовов для управления обучением)
A question I often get at this point from programmers in particular when experimenting with different numbers of epochs is, How can I stop training when I reach a point that I want to be at? What do I always have to hard code it to go for certain number of epochs? Well, the good news is that, the training loop does support callbacks. So in every epoch, you can callback to a code function, having checked the metrics. If they're what you want to say, then you can cancel the training at that point. Let's take a look. Okay, so here's our code for training the neural network to recognize the fashion images. In particular, keep an eye on the model.fit function that executes the training loop. You can see that here. What we'll now do is write a callback in Python. Here's the code. It's implemented as a separate class, but that can be in-line with your other code. It doesn't need to be in a separate file. In it, we'll implement the on_epoch_end function, which gets called by the callback whenever the epoch ends. It also sends a logs object which contains lots of great information about the current state of training. For example, the current loss is available in the logs, so we can query it for certain amount. For example, here I'm checking if the loss is less than 0.4 and canceling the training itself. Now that we have our callback, let's return to the rest of the code, and there are two modifications that we need to make. First, we instantiate the class that we just created, we do that with this code. Then, in my model.fit, I used the callbacks parameter and pass it this instance of the class. Let's see this in action.
---------------------------------------------------------------
Вопрос, который я на этом месте часто получаю от программистов, в особенности, при экспериментах с различным количеством эпох — это: как остановить обучение, если я достигну точки, к которой стремился? Почему мне вечно нужно всё хардкодить, чтобы выполнить нужное количество эпох? Хорошая новость заключается в том, что цикл обучения поддерживает обратные вызовы. Таким образом, в каждой эпохе вы можете выполнить обратный вызов вашей функции для проверки метрик. И если они совпадают с тем, что вам нужно, то вы можете прервать обучение образом. Давайте посмотрим. Вот он наш код для обучения нейронной сети на распознавание изображений одежды. В особенности, обратите внимание на функцию model.fit, которая выполняет цикл обучения. Она здесь. А сейчас мы напишем обратный вызов на Python. Вот его код. Он реализован как отдельный класс, но он может быть частью остального вашего кода. Его не обязательно выносить в отдельный файл. Внутри него мы напишем функцию on_epoch_end, которая будет вызываться через обратный вызов всякий раз, когда заканчивается эпоха. Обратный вызов также передаёт объект logs, который содержит кучу полезной информации о текущем состоянии обучения. Например, текущая потеря (loss) доступна в объекте logs. Таким образом, мы можем запросить его. Например, здесь я проверяю, является ли потеря менее 0.4, и если да — прерываю обучение. Теперь, когда у нас есть наш обратный вызов, давайте вернёмся к остальному коду и внесём в него два необходимых исправления. Во-первых, создадим экземпляр только что написанного класса, вот таким образом. Затем в model.fit воспользуемся параметром callbacks, и передадим в него экземпляр нашего класса. Давайте посмотрим на это в действии.

11(w2)-See how to implement Callbacks (Lab 2): (15.MLg_1c)

Experiment with using Callbacks in this notebook -- work through it to see how they perform!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W2/ungraded_labs/C1_W2_Lab_2_callbacks.ipynb
---------------------------------------------------------------
Поэкспериментируйте с использованием обратных вызовов в этой записной книжке — просмотрите ее, чтобы увидеть, как они работают!

12(w2)-video7: Walk through a notebook with Callbacks (15.MLg_1c)

Let's take a look at the code for callbacks, and see how it works. You can see the code here.
Here's the notebook with the code already written,and here's the class that we defined to handle the callback, and here is where we instantiate the callback class itself.
Finally, here's where we set up the callback to be called as part of the training loop. As we begin training, note that we asked it to train for five epochs. Now, keep an eye on the losses that trains. We want to break when it goes below 0.4, and by the end of the first epoch we're actually getting close already. As the second epoch begins, it has already dropped below 0.4, but the callback hasn't been hit yet. That's because we set it up for on epoch end. It's good practice to do this, because with some data and some algorithms, the loss may vary up and down during the epoch, because all of the data hasn't yet been processed. So, I like to wait for the end to be sure. Now the epoch has ended, we can see that the training ends, even though we've only done two epochs. Note that we're sure we asked for five epochs and that we ended after two, because the loss is below 0.4, which we checked for in the callback. It's pretty cool right?
---------------------------------------------------------------
Давайте взглянем на код с обратным вызовом, и посмотрим, как он работает. Здесь можно видеть этот код. Это блокнот с заранее написанным кодом, а вот класс, который мы написали для обработки обратного вызова. А вот здесь мы создаём сам экземпляр класса обратного вызова. И наконец, здесь мы устанавливаем сам обратный вызов, чтобы он мог быть вызван внутри цикла обучения. Обратите внимание, что при запуске обучения мы просили обучать сеть на протяжении пяти эпох. Следите за величиной потери в процессе обучения. Мы хотим прекратить обучение, как только loss опустится ниже 0.4, и уже к концу первой эпохи мы уже подобрались довольно близко к этому значению. На момент начала второй эпохи значение уже опустилось ниже 0.4, но обратный вызов пока ещё не сработал. Всё это потому что мы настроили его на срабатывание в конце эпохи. Такой вариант является хорошей практикой, т.к. на некоторых данных и с некоторыми алгоритмами потеря может колебаться то вверх, то вниз во время эпохи т.к. не все данные были ещё обработаны. Поэтому для надёжности я предпочитаю подождать до конца. Сейчас эпоха завершилась, потеря составляет 0.3563, и мы видим, что обучение окончено, несмотря на то, что мы выполнили всего две эпохи. Отметим, что мы запрашивали 5 эпох, а закончили после двух, т.к. потеря опустилась ниже 0.4, что мы и проверяли в обратном вызове. Круто, не правда ли?

13(w2)-video8: Week 2 Quiz: (15.MLg_1c)

1) What is the resolution of o the 70,000 images from the Fashion MNIST dataset?:
1. 82x82 Grayscale
2. 28x28 Grayscale (+)
3. 100x100 Color
4. 28x28 Color
2) Why are there 10 output neurons in the Neural Network used as an example for the Computer Vision Problem?:
1. There are 10 different labels (+)
2. Purely arbitrary
3. To make it classify 10x faster
4. To make it train 10x faster
3) What does Relu do?:
1. For a value x,, it returns 1/x
2. It only returns x if x is less than zero
3. It returns the negative of x
4. It only returns x if x is greater then zero(+)
4) Why do you split data into training and test sets?:
1. To make testing quicker
2. To train a network with previously unseen data
3. To test a network with previously unseen data(+)
4. To make training quicker
5)True or False: The on_epoch_end function sends a logs object with lots of great information about the current state of training at the start of every epoch:
1 False
6) Why do you set the callbacks=parameter in your fit function?:
1. So that the training loops performs all epochs
2. Because it accelerates the training
3. So. on every epoch you can call back to a code function(+)

14(w2)-Lecture Notes Week 2: (15.MLg_1c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.
https://www.deeplearning.ai
makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons.
https://www.deeplearning.ai
делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

15(w2)-Weekly Assignment: (15.MLg_1c)

Implementing Callbacks in TensorFlow using the MNIST Dataset
Week 2: Implementing Callbacks in TensorFlow using the MNIST Dataset:
In the course you learned how to do classification using Fashion MNIST, a data set containing items of clothing. There's another, similar dataset called MNIST which has items of handwriting -- the digits 0 through 9.
Write an MNIST classifier that trains to 99% accuracy and stops once this threshold is achieved. In the lecture you saw how this was done for the loss but here you will be using accuracy instead.
Some notes:
1.Your network should succeed in less than 9 epochs.
2. When it reaches 99% or greater it should print out the string "Reached 99% accuracy so cancelling training!" and stop training.
3. If you add any additional variables, make sure you use the same names as the ones used in the class. This is important for the function signatures (the parameters and names) of the callbacks.
---------------------------------------------------------------
Неделя 2: Реализация обратных вызовов в TensorFlow с использованием набора данных MNIST
В ходе курса вы узнали, как выполнять классификацию с использованием Fashion MNIST, набора данных, содержащего предметы одежды. Есть еще один похожий набор данных под названием MNIST, в котором есть элементы рукописного ввода — цифры от 0 до 9.
Напишите классификатор MNIST, который обучается с точностью 99% и останавливается при достижении этого порога. В лекции вы видели, как это делается для проигрыша, но здесь вместо этого вы будете использовать точность.
Некоторые примечания:
1. Ваша сеть должна быть успешной менее чем за 9 эпох.
2. Когда он достигает 99% или выше, он должен распечатать строку «Достигнута точность 99%, поэтому отмена обучения!» и прекратить тренировки.
3. Если вы добавляете какие-либо дополнительные переменные, убедитесь, что вы используете те же имена, что и в классе. Это важно для сигнатур функций (параметров и имен) обратных вызовов.

Create and train your model:
Now that you have defined your callback it is time to complete the train_mnist function below.
You must set your model to train for 10 epochs and the callback should fire before the 9th epoch for you to pass this assignment.
Hint:
Feel free to try the architecture for the neural network that you see fit but in case you need extra help you can check out an architecture that works pretty well at the end of this notebook.
---------------------------------------------------------------
Создайте и обучите свою модель:
Теперь, когда вы определили свой обратный вызов, пришло время завершить функцию train_mnist ниже.
Вы должны настроить свою модель на обучение в течение 10 эпох, и обратный вызов должен срабатывать до 9-й эпохи, чтобы вы могли пройти это задание.
Намекать:
Не стесняйтесь попробовать архитектуру нейронной сети, которую вы считаете подходящей, но если вам нужна дополнительная помощь, вы можете проверить архитектуру, которая работает довольно хорошо, в конце этой записной книжки.

NEXT week_3 (15.MLg_1c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3) Enhancing Vision with Convolutional Neural Networks (15.MLg_1c)

(Улучшение зрения с помощью сверточных нейронных сетей)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 18 minutes
Self-study: 2,16 hour
Graded tasks (Tasks to be assessed): 2

(w3) Introduction: (15.MLg_1c)

Welcome to week 3! In week 2 you saw a basic Neural Network for Computer Vision. It did the job nicely, but it was a little naive in its approach. This week we’ll see how to make it better, as discussed by Laurence and Andrew here.
---------------------------------------------------------------
Добро пожаловать на 3 неделю! На второй неделе вы увидели базовую нейронную сеть для компьютерного зрения. Он хорошо справлялся со своей задачей, но подход был немного наивен. На этой неделе мы посмотрим, как сделать его лучше, как обсуждали здесь Лоуренс и Эндрю.

(w3) Learning Objectives: (15.MLg_1c)

● Use callback functions to interrupt training after meeting a threshold accuracy
● Test the effect of adding convolution and MaxPooling to the neural network for classifying Fashion MNIST images on classification accuracy
● Explain and visualize how convolution and MaxPooling aid in image classification tasks
---------------------------------------------------------------
● Используйте функции обратного вызова, чтобы прервать обучение после достижения пороговой точности.
● Проверить влияние добавления свертки и MaxPooling в нейронную сеть для классификации изображений Fashion MNIST на точность классификации.
● Объясните и продемонстрируйте, как свертка и MaxPooling помогают в задачах классификации изображений.

1(w3)-video1: A conversation with Andrew Ng (15.MLg_1c)

The fashion and this data set was created by [inaudible] and [inaudible]. I think it's really cool that you're already able to implement a neural network to do this fashion classification task. It's just amazing that large data sets like this are readily available to students so that they can learn and it make it really easy to learn. And in this case we saw with just a few lines of code, we were able to build a DNN that allowed you to do this classification of clothing and we got reasonable accuracy with it but it was a little bit of a naive algorithm that we used, right? We're looking at every pixel in every image, but maybe there's ways that we can make it better but maybe looking at features of what makes a shoe a shoe and what makes a handbag a handbag. What do you think? Yeah. So one of the ideas that make these neural networks work much better is to use convolutional neural networks, where instead of looking at every single pixel and say, "Oh, that pixel has value 87, that has value 127." So is this a shoe or is this a hand bag? I don't know. But instead you can look at a picture and say, "Oh, I see shoelaces and a sole." Then, it's probably shoe or say, "I see a handle and rectangular bag beneath that." Probably a handbag. So confidence hopefully, we'll let the students do this. Sure, what's really interesting about convolutions is they sound complicated but they're actually quite straightforward, right? It's a filter that you pass over an image in the same way as if you're doing sharpening, if you've ever done image processing. It can spot features within the image as you've mentioned. With the same paradigm of just data labels, we can let a neural network figure out for itself that it should look for shoe laces and soles or handles in bags and just learn how to detect these things by itself. So shall we see what impact that would have on Fashion MNIST? So in the next video, you'll learn about convolutional neural networks and get to use it to build a much better fashion classifier.
---------------------------------------------------------------
Набор данных Fashion-MNIST был создан Han Xiao, Kashif Rasul и Abien Agarap. Я думаю, что это действительно здорово, что вы уже смогли реализовать нейронную сеть, чтобы выполнить задачу по классификации предметов одежды. Просто удивительно, что такие большие наборы данных, как этот, доступны студентам, позволяя им учиться, и благодаря этому им легче учиться. В данном случае, мы видели, как в несколько строк кода мы смогли построить DNN, которая позволила нам выполнить классификацию одежды, и мы получили неплохую точность, но мы использовали несколько наивный алгоритм, верно? Мы рассматриваем каждый пиксель в каждом изображении, но, возможно, у нас есть способы его улучшить — возможно, глядя на признаки, которые делают обувь обувью, или делают сумочку сумочкой. Что думаете? Да. Одним из вариантов заставить эти нейронные сети работать гораздо лучше является использование свёрточных нейронных сетей, где вместо изучения каждого пиксела в духе: «О, этот пиксел равен 87, а вот этот равен 127. Так это ботинок, или это сумочка? Не знаю.» Но вместо этого вы можете посмотреть на картинку и сказать: «O, я вижу шнурки и подошву. Тогда это, вероятно, обувь.» — или сказать, «Я вижу ручку и прямоугольный мешок под ней. Вероятно, это ручная сумочка.» Так что, полагаю, мы дадим студентам это сделать. Конечно. Что действительно любопытно в свёртках, так это то, что они выглядят очень сложными, но на самом деле довольно просты, верно? Это фильтр, через который вы пропускаете изображение так же, как если бы вы настраивали резкость — если вы когда-либо имели дело с обработкой изображений. Этот метод может выделить признаки из картинки, как вы и упоминали. Благодаря той же самой парадигме разметки данных мы можем позволить нейронной сети разобраться самой, что она должна искать: шнурки и подошвы, или ручки в сумках, — и просто научиться определять эти вещи самостоятельно. Итак, стоит посмотреть, к чему это приведет на Fashion MNIST? В следующем видео вы узнаете о свёрточных нейронных сетях и будете использовать их для построения улучшенного классификатора одежды.

2(w3)-video2: What are convolutions and pooling? (15.MLg_1c)

(Что такое свертки и пулы)
In the previous example, you saw how you could create a neural network called a deep neural network to pattern match a set of images of fashion items to labels. In just a couple of minutes, you're able to train it to classify with pretty high accuracy on the training set, but a little less on the test set. Now, one of the things that you would have seen when you looked at the images is that there's a lot of wasted space in each image. While there are only 784 pixels, it will be interesting to see if there was a way that we could condense the image down to the important features that distinguish what makes it a shoe, or a handbag, or a shirt. That's where convolutions come in. So, what's convolution? You might ask. Well, if you've ever done any kind of image processing, it usually involves having a filter and passing that filter over the image in order to change the underlying image. The process works a little bit like this. For every pixel, take its value, and take a look at the value of its neighbors. If our filter is three by three, then we can take a look at the immediate neighbor, so that you have a corresponding three by three grid. Then to get the new value for the pixel, we simply multiply each neighbor by the corresponding value in the filter. So, for example, in this case, our pixel has the value 192, and its upper left neighbor has the value zero. The upper left value and the filter is negative one, so we multiply zero by negative one. Then we would do the same for the upper neighbor. Its value is 64 and the corresponding filter value was zero, so we'd multiply those out. Repeat this for each neighbor and each corresponding filter value, and would then have the new pixel with the sum of each of the neighbor values multiplied by the corresponding filter value, and that's a convolution. It's really as simple as that. The idea here is that some convolutions will change the image in such a way that certain features in the image get emphasized. So, for example, if you look at this filter, then the vertical lines in the image really pop out. With this filter, the horizontal lines pop out. Now, that's a very basic introduction to what convolutions do, and when combined with something called pooling, they can become really powerful. But simply, pooling is a way of compressing an image. A quick and easy way to do this, is to go over the image of four pixels at a time, i.e, the current pixel and its neighbors underneath and to the right of it. Of these four, pick the biggest value and keep just that. So, for example, you can see it here. My 16 pixels on the left are turned into the four pixels on the right, by looking at them in two-by-two grids and picking the biggest value. This will preserve the features that were highlighted by the convolution, while simultaneously quartering the size of the image. We have the horizontal and vertical axes.
---------------------------------------------------------------
На предыдущем примере вы увидели, как можно создать нейронную сеть под названием "глубокая нейронная сеть", чтобы сопоставить набор изображений предметов одежды с их метками. Всего через пару минут вы сможете обучить её классификации с довольно высокой точностью на обучающем наборе данных, однако немного меньшей на тестовом наборе. Возможно, при просмотре изображений вы уже заметили, в числе прочего, что есть много бесполезного пространства в каждой картинке. Хотя там только 784 пикселей, было бы интересно посмотреть, есть ли способ сжать изображение до важных признаков, которые определяют отличия обуви или сумочки, или рубашки. Вот где вступают в действие свёртки. Вы, возможно, спросите: "А что такое свёртка?" Если вы хоть раз как-либо обрабатывали изображения, то обычно при этом используют фильтр, которым проходят по изображению, чтобы изменить исходное изображение. Этот процесс работает примерно так. Для каждого пикселя берём его значение, и смотрим на значения его соседей. Если наш фильтр три на три, тогда мы можем рассмотреть непосредственных соседей, таким образом, у вас есть соответствующая сетка три на три. Чтобы затем получить новое значение для пикселя, мы просто умножаем каждого соседа на соответствующее значение в фильтре. Так, например, в данном случае, наш пиксел имеет значение 192, а его верхний левый сосед имеет значение 0. Верхнее левое значение в фильтре -1, поэтому мы умножаем 0 на -1. Затем мы сделаем то же самое для верхнего соседа. Его значение = 64, а соответствующее значение в фильтре было равно 0, Поэтому мы их перемножаем. Повторяем это для каждого соседа и каждого соответствующего значения фильтра, и получим новый пиксел, равный сумме каждого соседнего значения, умноженного на соответствующее значение фильтра. Это и есть свёртка. Это действительно очень просто. Идея заключается в том, что некоторые свёртки будут изменять изображение таким образом, что определённые признаки на изображении станут более выраженными. Так например, если взять этот фильтр, то вертикальные линии на изображении действительно выделятся. Вот с таким фильтром выделятся горизонтальные линии. Это очень базовое введение в то, что делают свёртки, а в сочетании с тем, что называют объединением (pooling) — они могут стать очень мощными. Простым языком, объединение — это способ сжатия изображения. Быстрый и простой способ достичь этого — брать из изображения четыре пиксела за раз, т.е., текущий пиксел и его соседей снизу и справа от него. Из этих четырех выбрать самое большое значение, и оставить только его. Здесь представлен такой пример. Мои 16 пикселей слева превратились в четыре пиксела справа, если рассматривать их блоками 2x2 и выбирать наибольшее значение. Это сохранит признаки, которые были подчеркнуты свёрткой, одновременно уменьшая вчетверо размер изображения. У нас есть горизонтальная и вертикальная оси.

3(w3)-Coding convolutions and pooling layers: (15.MLg_1c)

(Свертки кодирования и объединение слоев)
The concepts introduced in this video are available as Conv2D layers and MaxPooling2D layers in TensorFlow. You’ll learn how to implement them in code in the next video.
https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D
https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPooling2D
tf.keras.layers.Conv2D
Conv2D осуществляет свертку двумерного входного слоя с ядром (фильтром) для создания нового выходного слоя. Каждая ячейка в новом слое представляет собой линейную комбинацию значений входных пикселей, взвешенных соответствующими значениями ядра.
Операция Conv2D является одной из ключевых операций в сверточных нейронных сетях (Convolutional Neural Networks, CNN). Они обладают способностью распознавать и извлекать визуальные признаки, такие как грани, текстуры или объекты из изображений, и широко применяются в обработке изображений, компьютерном зрении и других задачах, связанных с анализом визуальных данных.
tf.keras.layers.MaxPooling2D
MaxPooling2D - это операция пулинга (уменьшения размерности) в сверточных нейронных сетях. Она применяется к двумерному входному слою, например, после операции свертки (Conv2D), чтобы уменьшить размерность и извлечь наиболее значимую информацию.
Часто MaxPooling2D применяется после операции Conv2D для уменьшения размера пространственных областей и подавления шума. Обычно используются прямоугольные окна пулинга размером 2x2 или 3x3. Например, применение пулинга 2x2 к входному слою уменьшает его размерность вдвое.
---------------------------------------------------------------
Концепции, представленные в этом видео, доступны в виде слоев Conv2D и слоев MaxPooling2D в TensorFlow. В следующем видео вы узнаете, как реализовать их в коде.

4(w3)-video3: Implementing convolutional layers (15.MLg_1c)

(Реализация сверточных слоев)
So now let's take a look at convolutions and pooling in code. We don't have to do all the math for filtering and compressing, we simply define convolutional and pooling layers to do the job for us.
So here's our code from the earlier example, where we defined out a neural network to have an input layer in the shape of our data, and output layer in the shape of the number of categories we're trying to define, and a hidden layer in the middle. The Flatten takes our square 28 by 28 images and turns them into a one dimensional array.
To add convolutions to this, you use code like this. You'll see that the last three lines are the same, the Flatten, the Dense hidden layer with 128 neurons, and the Dense output layer with 10 neurons. What's different is what has been added on top of this. Let's take a look at this, line by line.
Here we're specifying the first convolution. We're asking keras to generate 64 filters for us. These filters are 3 by 3, their activation is relu, which means the negative values will be thrown way, and finally the input shape is as before, the 28 by 28. That extra 1 just means that we are tallying using a single byte for color depth. As we saw before our image is our gray scale, so we just use one byte.
Now, of course, you might wonder what the 64 filters are. It's a little beyond the scope of this class to define them, but they aren't random. They start with a set of known good filters in a similar way to the pattern fitting that you saw earlier, and the ones that work from that set are learned over time.
For more details on convolutions and how they work, there's a great set of resources here.
---------------------------------------------------------------
Итак, теперь давайте взглянем на свертки и объединение в коде. Нам не нужно делать всю математику для фильтрации и сжатия, мы просто определяем сверточные слои и слои объединения, которые делают эту работу за нас.
Итак, вот наш код из предыдущего примера, где мы определили нейронную сеть, чтобы иметь входной слой в форме наших данных и выходной слой в форме количества категорий, которые мы пытаемся определить, и скрытый слой в середине. Flatten берет наши квадратные изображения 28 на 28 и превращает их в одномерный массив.
Чтобы добавить свертки к этому, вы используете такой код. Вы увидите, что последние три строки одинаковы: Flatten, скрытый слой Dense со 128 нейронами и выходной слой Dense с 10 нейронами. Что отличается, так это то, что было добавлено поверх этого. Давайте посмотрим на это, строка за строкой.
Здесь мы указываем первую свертка. Мы просим keras сгенерировать для нас 64 фильтра. Эти фильтры 3 на 3, их активация relu, что означает, что отрицательные значения будут отбрасываться, и, наконец, входная форма такая же, как и раньше, 28 на 28. Эта дополнительная 1 просто означает, что мы подсчитываем, используя один байт для глубина цвета. Как мы видели ранее, наше изображение — это шкала серого, поэтому мы используем только один байт.
Теперь, конечно, вы можете задаться вопросом, что такое 64 фильтра. Их определение немного выходит за рамки этого класса, но они не случайны. Они начинаются с набора известных хороших фильтров, аналогично подбору шаблона, который вы видели ранее, а те, которые работают из этого набора, изучаются со временем.
Для получения более подробной информации о свертках и о том, как они работают, есть большой набор ресурсов здесь.
https://bit.ly/2UGa7uH

=======

10(w2)-video6: Using Callbacks to control training (15.MLg_1c)

(Использование обратных вызовов для управления обучением)
A question I often get at this point from programmers in particular when experimenting with different numbers of epochs is, How can I stop training when I reach a point that I want to be at? What do I always have to hard code it to go for certain number of epochs? Well, the good news is that, the training loop does support callbacks. So in every epoch, you can callback to a code function, having checked the metrics. If they're what you want to say, then you can cancel the training at that point. Let's take a look. Okay, so here's our code for training the neural network to recognize the fashion images. In particular, keep an eye on the model.fit function that executes the training loop. You can see that here. What we'll now do is write a callback in Python. Here's the code. It's implemented as a separate class, but that can be in-line with your other code. It doesn't need to be in a separate file. In it, we'll implement the on_epoch_end function, which gets called by the callback whenever the epoch ends. It also sends a logs object which contains lots of great information about the current state of training. For example, the current loss is available in the logs, so we can query it for certain amount. For example, here I'm checking if the loss is less than 0.4 and canceling the training itself. Now that we have our callback, let's return to the rest of the code, and there are two modifications that we need to make. First, we instantiate the class that we just created, we do that with this code. Then, in my model.fit, I used the callbacks parameter and pass it this instance of the class. Let's see this in action.
---------------------------------------------------------------
Вопрос, который я на этом месте часто получаю от программистов, в особенности, при экспериментах с различным количеством эпох — это: как остановить обучение, если я достигну точки, к которой стремился? Почему мне вечно нужно всё хардкодить, чтобы выполнить нужное количество эпох? Хорошая новость заключается в том, что цикл обучения поддерживает обратные вызовы. Таким образом, в каждой эпохе вы можете выполнить обратный вызов вашей функции для проверки метрик. И если они совпадают с тем, что вам нужно, то вы можете прервать обучение образом. Давайте посмотрим. Вот он наш код для обучения нейронной сети на распознавание изображений одежды. В особенности, обратите внимание на функцию model.fit, которая выполняет цикл обучения. Она здесь. А сейчас мы напишем обратный вызов на Python. Вот его код. Он реализован как отдельный класс, но он может быть частью остального вашего кода. Его не обязательно выносить в отдельный файл. Внутри него мы напишем функцию on_epoch_end, которая будет вызываться через обратный вызов всякий раз, когда заканчивается эпоха. Обратный вызов также передаёт объект logs, который содержит кучу полезной информации о текущем состоянии обучения. Например, текущая потеря (loss) доступна в объекте logs. Таким образом, мы можем запросить его. Например, здесь я проверяю, является ли потеря менее 0.4, и если да — прерываю обучение. Теперь, когда у нас есть наш обратный вызов, давайте вернёмся к остальному коду и внесём в него два необходимых исправления. Во-первых, создадим экземпляр только что написанного класса, вот таким образом. Затем в model.fit воспользуемся параметром callbacks, и передадим в него экземпляр нашего класса. Давайте посмотрим на это в действии.

11(w2)-See how to implement Callbacks (Lab 2): (15.MLg_1c)

Experiment with using Callbacks in this notebook -- work through it to see how they perform!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W2/ungraded_labs/C1_W2_Lab_2_callbacks.ipynb
---------------------------------------------------------------
Поэкспериментируйте с использованием обратных вызовов в этой записной книжке — просмотрите ее, чтобы увидеть, как они работают!

12(w2)-video7: Walk through a notebook with Callbacks (15.MLg_1c)

Let's take a look at the code for callbacks, and see how it works. You can see the code here.
Here's the notebook with the code already written,and here's the class that we defined to handle the callback, and here is where we instantiate the callback class itself.
Finally, here's where we set up the callback to be called as part of the training loop. As we begin training, note that we asked it to train for five epochs. Now, keep an eye on the losses that trains. We want to break when it goes below 0.4, and by the end of the first epoch we're actually getting close already. As the second epoch begins, it has already dropped below 0.4, but the callback hasn't been hit yet. That's because we set it up for on epoch end. It's good practice to do this, because with some data and some algorithms, the loss may vary up and down during the epoch, because all of the data hasn't yet been processed. So, I like to wait for the end to be sure. Now the epoch has ended, we can see that the training ends, even though we've only done two epochs. Note that we're sure we asked for five epochs and that we ended after two, because the loss is below 0.4, which we checked for in the callback. It's pretty cool right?
---------------------------------------------------------------
Давайте взглянем на код с обратным вызовом, и посмотрим, как он работает. Здесь можно видеть этот код. Это блокнот с заранее написанным кодом, а вот класс, который мы написали для обработки обратного вызова. А вот здесь мы создаём сам экземпляр класса обратного вызова. И наконец, здесь мы устанавливаем сам обратный вызов, чтобы он мог быть вызван внутри цикла обучения. Обратите внимание, что при запуске обучения мы просили обучать сеть на протяжении пяти эпох. Следите за величиной потери в процессе обучения. Мы хотим прекратить обучение, как только loss опустится ниже 0.4, и уже к концу первой эпохи мы уже подобрались довольно близко к этому значению. На момент начала второй эпохи значение уже опустилось ниже 0.4, но обратный вызов пока ещё не сработал. Всё это потому что мы настроили его на срабатывание в конце эпохи. Такой вариант является хорошей практикой, т.к. на некоторых данных и с некоторыми алгоритмами потеря может колебаться то вверх, то вниз во время эпохи т.к. не все данные были ещё обработаны. Поэтому для надёжности я предпочитаю подождать до конца. Сейчас эпоха завершилась, потеря составляет 0.3563, и мы видим, что обучение окончено, несмотря на то, что мы выполнили всего две эпохи. Отметим, что мы запрашивали 5 эпох, а закончили после двух, т.к. потеря опустилась ниже 0.4, что мы и проверяли в обратном вызове. Круто, не правда ли?

13(w2)-video8: Week 2 Quiz: (15.MLg_1c)

1) What is the resolution of o the 70,000 images from the Fashion MNIST dataset?:
1. 82x82 Grayscale
2. 28x28 Grayscale (+)
3. 100x100 Color
4. 28x28 Color
2) Why are there 10 output neurons in the Neural Network used as an example for the Computer Vision Problem?:
1. There are 10 different labels (+)
2. Purely arbitrary
3. To make it classify 10x faster
4. To make it train 10x faster
3) What does Relu do?:
1. For a value x,, it returns 1/x
2. It only returns x if x is less than zero
3. It returns the negative of x
4. It only returns x if x is greater then zero(+)
4) Why do you split data into training and test sets?:
1. To make testing quicker
2. To train a network with previously unseen data
3. To test a network with previously unseen data(+)
4. To make training quicker
5)True or False: The on_epoch_end function sends a logs object with lots of great information about the current state of training at the start of every epoch:
1 False
6) Why do you set the callbacks=parameter in your fit function?:
1. So that the training loops performs all epochs
2. Because it accelerates the training
3. So. on every epoch you can call back to a code function(+)

14(w2)-Lecture Notes Week 2: (15.MLg_1c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.
https://www.deeplearning.ai
makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons.
https://www.deeplearning.ai
делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

15(w2)-Weekly Assignment: (15.MLg_1c)

Implementing Callbacks in TensorFlow using the MNIST Dataset
Week 2: Implementing Callbacks in TensorFlow using the MNIST Dataset:
In the course you learned how to do classification using Fashion MNIST, a data set containing items of clothing. There's another, similar dataset called MNIST which has items of handwriting -- the digits 0 through 9.
Write an MNIST classifier that trains to 99% accuracy and stops once this threshold is achieved. In the lecture you saw how this was done for the loss but here you will be using accuracy instead.
Some notes:
1.Your network should succeed in less than 9 epochs.
2. When it reaches 99% or greater it should print out the string "Reached 99% accuracy so cancelling training!" and stop training.
3. If you add any additional variables, make sure you use the same names as the ones used in the class. This is important for the function signatures (the parameters and names) of the callbacks.
---------------------------------------------------------------
Неделя 2: Реализация обратных вызовов в TensorFlow с использованием набора данных MNIST
В ходе курса вы узнали, как выполнять классификацию с использованием Fashion MNIST, набора данных, содержащего предметы одежды. Есть еще один похожий набор данных под названием MNIST, в котором есть элементы рукописного ввода — цифры от 0 до 9.
Напишите классификатор MNIST, который обучается с точностью 99% и останавливается при достижении этого порога. В лекции вы видели, как это делается для проигрыша, но здесь вместо этого вы будете использовать точность.
Некоторые примечания:
1. Ваша сеть должна быть успешной менее чем за 9 эпох.
2. Когда он достигает 99% или выше, он должен распечатать строку «Достигнута точность 99%, поэтому отмена обучения!» и прекратить тренировки.
3. Если вы добавляете какие-либо дополнительные переменные, убедитесь, что вы используете те же имена, что и в классе. Это важно для сигнатур функций (параметров и имен) обратных вызовов.

Create and train your model:
Now that you have defined your callback it is time to complete the train_mnist function below.
You must set your model to train for 10 epochs and the callback should fire before the 9th epoch for you to pass this assignment.
Hint:
Feel free to try the architecture for the neural network that you see fit but in case you need extra help you can check out an architecture that works pretty well at the end of this notebook.
---------------------------------------------------------------
Создайте и обучите свою модель:
Теперь, когда вы определили свой обратный вызов, пришло время завершить функцию train_mnist ниже.
Вы должны настроить свою модель на обучение в течение 10 эпох, и обратный вызов должен срабатывать до 9-й эпохи, чтобы вы могли пройти это задание.
Намекать:
Не стесняйтесь попробовать архитектуру нейронной сети, которую вы считаете подходящей, но если вам нужна дополнительная помощь, вы можете проверить архитектуру, которая работает довольно хорошо, в конце этой записной книжки.

NEXT week_3 (15.MLg_1c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3) Enhancing Vision with Convolutional Neural Networks (15.MLg_1c)

(Улучшение зрения с помощью сверточных нейронных сетей)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 18 minutes
Self-study: 2,16 hour
Graded tasks (Tasks to be assessed): 2

(w3) Introduction: (15.MLg_1c)

Welcome to week 3! In week 2 you saw a basic Neural Network for Computer Vision. It did the job nicely, but it was a little naive in its approach. This week we’ll see how to make it better, as discussed by Laurence and Andrew here.
---------------------------------------------------------------
Добро пожаловать на 3 неделю! На второй неделе вы увидели базовую нейронную сеть для компьютерного зрения. Он хорошо справлялся со своей задачей, но подход был немного наивен. На этой неделе мы посмотрим, как сделать его лучше, как обсуждали здесь Лоуренс и Эндрю.

(w3) Learning Objectives: (15.MLg_1c)

● Use callback functions to interrupt training after meeting a threshold accuracy
● Test the effect of adding convolution and MaxPooling to the neural network for classifying Fashion MNIST images on classification accuracy
● Explain and visualize how convolution and MaxPooling aid in image classification tasks
---------------------------------------------------------------
● Используйте функции обратного вызова, чтобы прервать обучение после достижения пороговой точности.
● Проверить влияние добавления свертки и MaxPooling в нейронную сеть для классификации изображений Fashion MNIST на точность классификации.
● Объясните и продемонстрируйте, как свертка и MaxPooling помогают в задачах классификации изображений.

1(w3)-video1: A conversation with Andrew Ng (15.MLg_1c)

The fashion and this data set was created by [inaudible] and [inaudible]. I think it's really cool that you're already able to implement a neural network to do this fashion classification task. It's just amazing that large data sets like this are readily available to students so that they can learn and it make it really easy to learn. And in this case we saw with just a few lines of code, we were able to build a DNN that allowed you to do this classification of clothing and we got reasonable accuracy with it but it was a little bit of a naive algorithm that we used, right? We're looking at every pixel in every image, but maybe there's ways that we can make it better but maybe looking at features of what makes a shoe a shoe and what makes a handbag a handbag. What do you think? Yeah. So one of the ideas that make these neural networks work much better is to use convolutional neural networks, where instead of looking at every single pixel and say, "Oh, that pixel has value 87, that has value 127." So is this a shoe or is this a hand bag? I don't know. But instead you can look at a picture and say, "Oh, I see shoelaces and a sole." Then, it's probably shoe or say, "I see a handle and rectangular bag beneath that." Probably a handbag. So confidence hopefully, we'll let the students do this. Sure, what's really interesting about convolutions is they sound complicated but they're actually quite straightforward, right? It's a filter that you pass over an image in the same way as if you're doing sharpening, if you've ever done image processing. It can spot features within the image as you've mentioned. With the same paradigm of just data labels, we can let a neural network figure out for itself that it should look for shoe laces and soles or handles in bags and just learn how to detect these things by itself. So shall we see what impact that would have on Fashion MNIST? So in the next video, you'll learn about convolutional neural networks and get to use it to build a much better fashion classifier.
---------------------------------------------------------------
Набор данных Fashion-MNIST был создан Han Xiao, Kashif Rasul и Abien Agarap. Я думаю, что это действительно здорово, что вы уже смогли реализовать нейронную сеть, чтобы выполнить задачу по классификации предметов одежды. Просто удивительно, что такие большие наборы данных, как этот, доступны студентам, позволяя им учиться, и благодаря этому им легче учиться. В данном случае, мы видели, как в несколько строк кода мы смогли построить DNN, которая позволила нам выполнить классификацию одежды, и мы получили неплохую точность, но мы использовали несколько наивный алгоритм, верно? Мы рассматриваем каждый пиксель в каждом изображении, но, возможно, у нас есть способы его улучшить — возможно, глядя на признаки, которые делают обувь обувью, или делают сумочку сумочкой. Что думаете? Да. Одним из вариантов заставить эти нейронные сети работать гораздо лучше является использование свёрточных нейронных сетей, где вместо изучения каждого пиксела в духе: «О, этот пиксел равен 87, а вот этот равен 127. Так это ботинок, или это сумочка? Не знаю.» Но вместо этого вы можете посмотреть на картинку и сказать: «O, я вижу шнурки и подошву. Тогда это, вероятно, обувь.» — или сказать, «Я вижу ручку и прямоугольный мешок под ней. Вероятно, это ручная сумочка.» Так что, полагаю, мы дадим студентам это сделать. Конечно. Что действительно любопытно в свёртках, так это то, что они выглядят очень сложными, но на самом деле довольно просты, верно? Это фильтр, через который вы пропускаете изображение так же, как если бы вы настраивали резкость — если вы когда-либо имели дело с обработкой изображений. Этот метод может выделить признаки из картинки, как вы и упоминали. Благодаря той же самой парадигме разметки данных мы можем позволить нейронной сети разобраться самой, что она должна искать: шнурки и подошвы, или ручки в сумках, — и просто научиться определять эти вещи самостоятельно. Итак, стоит посмотреть, к чему это приведет на Fashion MNIST? В следующем видео вы узнаете о свёрточных нейронных сетях и будете использовать их для построения улучшенного классификатора одежды.

2(w3)-video2: What are convolutions and pooling? (15.MLg_1c)

(Что такое свертки и пулы)
In the previous example, you saw how you could create a neural network called a deep neural network to pattern match a set of images of fashion items to labels. In just a couple of minutes, you're able to train it to classify with pretty high accuracy on the training set, but a little less on the test set. Now, one of the things that you would have seen when you looked at the images is that there's a lot of wasted space in each image. While there are only 784 pixels, it will be interesting to see if there was a way that we could condense the image down to the important features that distinguish what makes it a shoe, or a handbag, or a shirt. That's where convolutions come in. So, what's convolution? You might ask. Well, if you've ever done any kind of image processing, it usually involves having a filter and passing that filter over the image in order to change the underlying image. The process works a little bit like this. For every pixel, take its value, and take a look at the value of its neighbors. If our filter is three by three, then we can take a look at the immediate neighbor, so that you have a corresponding three by three grid. Then to get the new value for the pixel, we simply multiply each neighbor by the corresponding value in the filter. So, for example, in this case, our pixel has the value 192, and its upper left neighbor has the value zero. The upper left value and the filter is negative one, so we multiply zero by negative one. Then we would do the same for the upper neighbor. Its value is 64 and the corresponding filter value was zero, so we'd multiply those out. Repeat this for each neighbor and each corresponding filter value, and would then have the new pixel with the sum of each of the neighbor values multiplied by the corresponding filter value, and that's a convolution. It's really as simple as that. The idea here is that some convolutions will change the image in such a way that certain features in the image get emphasized. So, for example, if you look at this filter, then the vertical lines in the image really pop out. With this filter, the horizontal lines pop out. Now, that's a very basic introduction to what convolutions do, and when combined with something called pooling, they can become really powerful. But simply, pooling is a way of compressing an image. A quick and easy way to do this, is to go over the image of four pixels at a time, i.e, the current pixel and its neighbors underneath and to the right of it. Of these four, pick the biggest value and keep just that. So, for example, you can see it here. My 16 pixels on the left are turned into the four pixels on the right, by looking at them in two-by-two grids and picking the biggest value. This will preserve the features that were highlighted by the convolution, while simultaneously quartering the size of the image. We have the horizontal and vertical axes.
---------------------------------------------------------------
На предыдущем примере вы увидели, как можно создать нейронную сеть под названием "глубокая нейронная сеть", чтобы сопоставить набор изображений предметов одежды с их метками. Всего через пару минут вы сможете обучить её классификации с довольно высокой точностью на обучающем наборе данных, однако немного меньшей на тестовом наборе. Возможно, при просмотре изображений вы уже заметили, в числе прочего, что есть много бесполезного пространства в каждой картинке. Хотя там только 784 пикселей, было бы интересно посмотреть, есть ли способ сжать изображение до важных признаков, которые определяют отличия обуви или сумочки, или рубашки. Вот где вступают в действие свёртки. Вы, возможно, спросите: "А что такое свёртка?" Если вы хоть раз как-либо обрабатывали изображения, то обычно при этом используют фильтр, которым проходят по изображению, чтобы изменить исходное изображение. Этот процесс работает примерно так. Для каждого пикселя берём его значение, и смотрим на значения его соседей. Если наш фильтр три на три, тогда мы можем рассмотреть непосредственных соседей, таким образом, у вас есть соответствующая сетка три на три. Чтобы затем получить новое значение для пикселя, мы просто умножаем каждого соседа на соответствующее значение в фильтре. Так, например, в данном случае, наш пиксел имеет значение 192, а его верхний левый сосед имеет значение 0. Верхнее левое значение в фильтре -1, поэтому мы умножаем 0 на -1. Затем мы сделаем то же самое для верхнего соседа. Его значение = 64, а соответствующее значение в фильтре было равно 0, Поэтому мы их перемножаем. Повторяем это для каждого соседа и каждого соответствующего значения фильтра, и получим новый пиксел, равный сумме каждого соседнего значения, умноженного на соответствующее значение фильтра. Это и есть свёртка. Это действительно очень просто. Идея заключается в том, что некоторые свёртки будут изменять изображение таким образом, что определённые признаки на изображении станут более выраженными. Так например, если взять этот фильтр, то вертикальные линии на изображении действительно выделятся. Вот с таким фильтром выделятся горизонтальные линии. Это очень базовое введение в то, что делают свёртки, а в сочетании с тем, что называют объединением (pooling) — они могут стать очень мощными. Простым языком, объединение — это способ сжатия изображения. Быстрый и простой способ достичь этого — брать из изображения четыре пиксела за раз, т.е., текущий пиксел и его соседей снизу и справа от него. Из этих четырех выбрать самое большое значение, и оставить только его. Здесь представлен такой пример. Мои 16 пикселей слева превратились в четыре пиксела справа, если рассматривать их блоками 2x2 и выбирать наибольшее значение. Это сохранит признаки, которые были подчеркнуты свёрткой, одновременно уменьшая вчетверо размер изображения. У нас есть горизонтальная и вертикальная оси.

3(w3)-Coding convolutions and pooling layers: (15.MLg_1c)

(Свертки кодирования и объединение слоев)
The concepts introduced in this video are available as Conv2D layers and MaxPooling2D layers in TensorFlow. You’ll learn how to implement them in code in the next video.
https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D
https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPooling2D
tf.keras.layers.Conv2D
Conv2D осуществляет свертку двумерного входного слоя с ядром (фильтром) для создания нового выходного слоя. Каждая ячейка в новом слое представляет собой линейную комбинацию значений входных пикселей, взвешенных соответствующими значениями ядра.
Операция Conv2D является одной из ключевых операций в сверточных нейронных сетях (Convolutional Neural Networks, CNN). Они обладают способностью распознавать и извлекать визуальные признаки, такие как грани, текстуры или объекты из изображений, и широко применяются в обработке изображений, компьютерном зрении и других задачах, связанных с анализом визуальных данных.
tf.keras.layers.MaxPooling2D
MaxPooling2D - это операция пулинга (уменьшения размерности) в сверточных нейронных сетях. Она применяется к двумерному входному слою, например, после операции свертки (Conv2D), чтобы уменьшить размерность и извлечь наиболее значимую информацию.
Часто MaxPooling2D применяется после операции Conv2D для уменьшения размера пространственных областей и подавления шума. Обычно используются прямоугольные окна пулинга размером 2x2 или 3x3. Например, применение пулинга 2x2 к входному слою уменьшает его размерность вдвое.
---------------------------------------------------------------
Концепции, представленные в этом видео, доступны в виде слоев Conv2D и слоев MaxPooling2D в TensorFlow. В следующем видео вы узнаете, как реализовать их в коде.

4(w3)-video3: Implementing convolutional layers (15.MLg_1c)

(Реализация сверточных слоев)
So now let's take a look at convolutions and pooling in code. We don't have to do all the math for filtering and compressing, we simply define convolutional and pooling layers to do the job for us.
So here's our code from the earlier example, where we defined out a neural network to have an input layer in the shape of our data, and output layer in the shape of the number of categories we're trying to define, and a hidden layer in the middle. The Flatten takes our square 28 by 28 images and turns them into a one dimensional array.
To add convolutions to this, you use code like this. You'll see that the last three lines are the same, the Flatten, the Dense hidden layer with 128 neurons, and the Dense output layer with 10 neurons. What's different is what has been added on top of this. Let's take a look at this, line by line.
Here we're specifying the first convolution. We're asking keras to generate 64 filters for us. These filters are 3 by 3, their activation is relu, which means the negative values will be thrown way, and finally the input shape is as before, the 28 by 28. That extra 1 just means that we are tallying using a single byte for color depth. As we saw before our image is our gray scale, so we just use one byte.
Now, of course, you might wonder what the 64 filters are. It's a little beyond the scope of this class to define them, but they aren't random. They start with a set of known good filters in a similar way to the pattern fitting that you saw earlier, and the ones that work from that set are learned over time.
For more details on convolutions and how they work, there's a great set of resources here.
---------------------------------------------------------------
Итак, теперь давайте взглянем на свертки и объединение в коде. Нам не нужно делать всю математику для фильтрации и сжатия, мы просто определяем сверточные слои и слои объединения, которые делают эту работу за нас.
Итак, вот наш код из предыдущего примера, где мы определили нейронную сеть, чтобы иметь входной слой в форме наших данных и выходной слой в форме количества категорий, которые мы пытаемся определить, и скрытый слой в середине. Flatten берет наши квадратные изображения 28 на 28 и превращает их в одномерный массив.
Чтобы добавить свертки к этому, вы используете такой код. Вы увидите, что последние три строки одинаковы: Flatten, скрытый слой Dense со 128 нейронами и выходной слой Dense с 10 нейронами. Что отличается, так это то, что было добавлено поверх этого. Давайте посмотрим на это, строка за строкой.
Здесь мы указываем первую свертка. Мы просим keras сгенерировать для нас 64 фильтра. Эти фильтры 3 на 3, их активация relu, что означает, что отрицательные значения будут отбрасываться, и, наконец, входная форма такая же, как и раньше, 28 на 28. Эта дополнительная 1 просто означает, что мы подсчитываем, используя один байт для глубина цвета. Как мы видели ранее, наше изображение — это шкала серого, поэтому мы используем только один байт.
Теперь, конечно, вы можете задаться вопросом, что такое 64 фильтра. Их определение немного выходит за рамки этого класса, но они не случайны. Они начинаются с набора известных хороших фильтров, аналогично подбору шаблона, который вы видели ранее, а те, которые работают из этого набора, изучаются со временем.
Для получения более подробной информации о свертках и о том, как они работают, есть большой набор ресурсов здесь.
https://bit.ly/2UGa7uH

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# next code
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),

    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

5(w3)-Learn more about convolutions: (15.MLg_1c)

(Узнать больше о свертках)
You’ve seen how to add a convolutional 2D layer to the top of your neural network in the previous video. If you want to see more detail on how they work, check out the playlist at https://bit.ly/2UGa7uH. But do take note that it is not required to complete this course.
Now let’s take a look at adding the pooling, and finishing off the convolutions so you can try them out…
---------------------------------------------------------------
Вы видели, как добавить сверточный 2D-слой в верхнюю часть вашей нейронной сети в предыдущем видео. Если вы хотите узнать больше о том, как они работают, ознакомьтесь с плейлистом на странице https://bit.ly/2UGa7uH. Но обратите внимание, что проходить этот курс не обязательно.
Теперь давайте взглянем на добавление объединения и завершение сверток, чтобы вы могли попробовать их…

6(w3)-video4: Implementing pooling layers (15.MLg_1c)

(Реализация объединенных слоев)
This next line of code will then create a pooling layer. It's max-pooling because we're going to take the maximum value. We're saying it's a two-by-two pool, so for every four pixels, the biggest one will survive as shown earlier. We then add another convolutional layer, and another max-pooling layer so that the network can learn another set of convolutions on top of the existing one, and then again, pool to reduce the size. So, by the time the image gets to the flatten to go into the dense layers, it's already much smaller. It's being quartered, and then quartered again. So, its content has been greatly simplified, the goal being that the convolutions will filter it to the features that determine the output. A really useful method on the model is the model.summary method. This allows you to inspect the layers of the model, and see the journey of the image through the convolutions, and here is the output. It's a nice table showing us the layers, and some details about them including the output shape. It's important to keep an eye on the output shape column. When you first look at this, it can be a little bit confusing and feel like a bug. After all, isn't the data 28 by 28, so y is the output, 26 by 26. The key to this is remembering that the filter is a three by three filter. Consider what happens when you start scanning through an image starting on the top left. So, for example with this image of the dog on the right, you can see zoomed into the pixels at its top left corner. You can't calculate the filter for the pixel in the top left, because it doesn't have any neighbors above it or to its left. In a similar fashion, the next pixel to the right won't work either because it doesn't have any neighbors above it. So, logically, the first pixel that you can do calculations on is this one, because this one of course has all eight neighbors that a three by three filter needs. This when you think about it, means that you can't use a one pixel margin all around the image, so the output of the convolution will be two pixels smaller on x, and two pixels smaller on y. If your filter is five-by-five for similar reasons, your output will be four smaller on x, and four smaller on y. So, that's y with a three by three filter, our output from the 28 by 28 image, is now 26 by 26, we've removed that one pixel on x and y, and each of the borders. So, next is the first of the max-pooling layers. Now, remember we specified it to be two-by-two, thus turning four pixels into one, and having our x and y. So, now our output gets reduced from 26 by 26, to 13 by 13. The convolutions will then operate on that, and of course, we lose the one pixel margin as before, so we're down to 11 by 11, add another two-by-two max-pooling to have this rounding down, and went down, down to five-by-five images. So, now our dense neural network is the same as before, but it's being fed with five-by-five images instead of 28 by 28 ones. But remember, it's not just one compress five-by-five image instead of the original 28 by 28, there are a number of convolutions per image that we specified, in this case 64. So, there are 64 new images of five-by-five that had been fed in. Flatten that out and you have 25 pixels times 64, which is 1600. So, you can see that the new flattened layer has 1,600 elements in it, as opposed to the 784 that you had previously. This number is impacted by the parameters that you set when defining the convolutional 2D layers. Later when you experiment, you'll see what the impact of setting what other values for the number of convolutions will be, and in particular, you can see what happens when you're feeding less than 784 over all pixels in. Training should be faster, but is there a sweet spot where it's more accurate? Well, let's switch to the workbook, and we can try it out for ourselves.
---------------------------------------------------------------
Следующая строчка кода создаст слой пулинга. Мы выбрали MaxPooling2D, поскольку мы хотим брать максимальное значение. Мы говорим, что это будет пул 2х2, поэтому из каждых четырёх пикселов выживет набольшее значение, как было показано ранее. Мы затем добавим еще один свёрточный слой Conv2D и еще один слой MaxPooling2D, так что сеть сможет выучить ещё один набор свёрток поверх уже существующего, а затем — опять пулинг, чтобы уменьшить размер. Так к моменту, когда изображение доходит до слоя Flatten, чтобы попасть в Dense-слои, оно уже гораздо меньше, чем раньше. Изображение уменьшается в 4 раза, а затем ещё в 4 раза. Таким образом, его содержимое значительно упрощается, и цель в том, что свёртки выберут из изображения признаки, определяющие выход сети. Действительно полезный метод в модели — это метод model.summary(). Он позволяет проинспектировать слои модели, и просмотреть весь путь, который проходит изображение через свёртки. Вот что он выводит. Эта классная табличка показывает нам слои и некоторые сведения о них, включая размерность выхода. Стоит обращать внимание на столбец с размерностью выхода. Когда вы первый раз смотрите на него, его вид может немного сбивать с толку и казаться ошибочным. Во-первых, размер у данных 28х28, так почему же на выходе имеем 26х26? Ключ к пониманию здесь — вспомнить, что фильтр имеет размер 3х3. Рассмотрим, что происходит, когда вы начинаете сканирование изображения, начиная с левого верхнего угла. Так, на примере этого изображения собаки (справа) вы можете увидеть фрагмент в верхнем левом углу, увеличенный до пикселов. Вы не можете посчитать фильтр для пиксела в левом верхнем углу, потому что у него нет никаких соседей выше или слева от него. Аналогичным образом, для следующего от него пиксела правее — это также не сработает, т.к. у нет соседей выше него. Поэтому логично, что первый пиксел, для которого можно сделать расчёт — вот этот, потому что у него есть все восемь соседей, необходимые фильтру. И если подумать, это означает, что нельзя использовать поле шириной в один пиксель по периметру всего изображения, и потому результат свёртки будет на 2 пиксела меньше по оси Х, и на 2 пиксела меньше по оси Y. Если ваш фильтр имеет размерность 5х5, то по тем же причинам, результат будет на 4 пиксела меньше по оси Х, и на 4 пиксела меньше по оси Y. Таким образом, в случае фильтра 3х3, выходным для изображения 28х28 — будет 26х26. Мы удалили тот один пиксель по X и по Y с каждой стороны. Далее идёт первый из MaxPooling слоёв. Вспомните, что мы определили его как 2х2, что превращает 4 пиксела в один по X и по Y. Так что теперь наш выход сократился с 26х26, до 13х13. Свёртки будут дальше работать с ним, и конечно, мы опять теряем поле в 1 пиксел, и размер понижается до 11х11, мы добавляем ещё один MaxPooling 2х2, чтобы сжать изображение, и так снижаем размер изображений до 5х5. Наша полносвязная нейронная сеть остаётся такой же, как прежде, но теперь она принимает на вход изображения размерностью 5х5 вместо картинок 28х28. Но запомните — это не просто единственное сжатое до 5х5 изображение — вместо оригинального 28х28. Это ряд свёрток для каждого изображения, которые мы определили. В нашем случае —их 64. Таким образом, у нас есть 64 новых изображения размерностью 5х5, которые подаются на вход. Развернув их, мы получим 25 пикселов * 64 изображения = 1600 пикселов. Как видите, в новом развернутом слое содержится 1600 элементов, в отличие от 784, как было ранее. Это число зависит от параметров, которые мы устанавливаем, определяя двумерные свёрточные слои. Позже, когда вы будете экспериментировать, то увидите, как повлияет подстановка других значений количества свёрток, и, в частности, увидите, что произойдёт, если подать на вход сети меньше чем 784 пикселов. Обучение должно пойти быстрее, но есть ли точка оптимума, где результат более точный? Давайте переключимся на workbook и попробуем сделать это самостоятельно.

=======

5(w3)-Learn more about convolutions: (15.MLg_1c)

(Узнать больше о свертках)
You’ve seen how to add a convolutional 2D layer to the top of your neural network in the previous video. If you want to see more detail on how they work, check out the playlist at https://bit.ly/2UGa7uH. But do take note that it is not required to complete this course.
Now let’s take a look at adding the pooling, and finishing off the convolutions so you can try them out…
---------------------------------------------------------------
Вы видели, как добавить сверточный 2D-слой в верхнюю часть вашей нейронной сети в предыдущем видео. Если вы хотите узнать больше о том, как они работают, ознакомьтесь с плейлистом на странице https://bit.ly/2UGa7uH. Но обратите внимание, что проходить этот курс не обязательно.
Теперь давайте взглянем на добавление объединения и завершение сверток, чтобы вы могли попробовать их…

6(w3)-video4: Implementing pooling layers (15.MLg_1c)

(Реализация объединенных слоев)
This next line of code will then create a pooling layer. It's max-pooling because we're going to take the maximum value. We're saying it's a two-by-two pool, so for every four pixels, the biggest one will survive as shown earlier. We then add another convolutional layer, and another max-pooling layer so that the network can learn another set of convolutions on top of the existing one, and then again, pool to reduce the size. So, by the time the image gets to the flatten to go into the dense layers, it's already much smaller. It's being quartered, and then quartered again. So, its content has been greatly simplified, the goal being that the convolutions will filter it to the features that determine the output. A really useful method on the model is the model.summary method. This allows you to inspect the layers of the model, and see the journey of the image through the convolutions, and here is the output. It's a nice table showing us the layers, and some details about them including the output shape. It's important to keep an eye on the output shape column. When you first look at this, it can be a little bit confusing and feel like a bug. After all, isn't the data 28 by 28, so y is the output, 26 by 26. The key to this is remembering that the filter is a three by three filter. Consider what happens when you start scanning through an image starting on the top left. So, for example with this image of the dog on the right, you can see zoomed into the pixels at its top left corner. You can't calculate the filter for the pixel in the top left, because it doesn't have any neighbors above it or to its left. In a similar fashion, the next pixel to the right won't work either because it doesn't have any neighbors above it. So, logically, the first pixel that you can do calculations on is this one, because this one of course has all eight neighbors that a three by three filter needs. This when you think about it, means that you can't use a one pixel margin all around the image, so the output of the convolution will be two pixels smaller on x, and two pixels smaller on y. If your filter is five-by-five for similar reasons, your output will be four smaller on x, and four smaller on y. So, that's y with a three by three filter, our output from the 28 by 28 image, is now 26 by 26, we've removed that one pixel on x and y, and each of the borders. So, next is the first of the max-pooling layers. Now, remember we specified it to be two-by-two, thus turning four pixels into one, and having our x and y. So, now our output gets reduced from 26 by 26, to 13 by 13. The convolutions will then operate on that, and of course, we lose the one pixel margin as before, so we're down to 11 by 11, add another two-by-two max-pooling to have this rounding down, and went down, down to five-by-five images. So, now our dense neural network is the same as before, but it's being fed with five-by-five images instead of 28 by 28 ones. But remember, it's not just one compress five-by-five image instead of the original 28 by 28, there are a number of convolutions per image that we specified, in this case 64. So, there are 64 new images of five-by-five that had been fed in. Flatten that out and you have 25 pixels times 64, which is 1600. So, you can see that the new flattened layer has 1,600 elements in it, as opposed to the 784 that you had previously. This number is impacted by the parameters that you set when defining the convolutional 2D layers. Later when you experiment, you'll see what the impact of setting what other values for the number of convolutions will be, and in particular, you can see what happens when you're feeding less than 784 over all pixels in. Training should be faster, but is there a sweet spot where it's more accurate? Well, let's switch to the workbook, and we can try it out for ourselves.
---------------------------------------------------------------
Следующая строчка кода создаст слой пулинга. Мы выбрали MaxPooling2D, поскольку мы хотим брать максимальное значение. Мы говорим, что это будет пул 2х2, поэтому из каждых четырёх пикселов выживет набольшее значение, как было показано ранее. Мы затем добавим еще один свёрточный слой Conv2D и еще один слой MaxPooling2D, так что сеть сможет выучить ещё один набор свёрток поверх уже существующего, а затем — опять пулинг, чтобы уменьшить размер. Так к моменту, когда изображение доходит до слоя Flatten, чтобы попасть в Dense-слои, оно уже гораздо меньше, чем раньше. Изображение уменьшается в 4 раза, а затем ещё в 4 раза. Таким образом, его содержимое значительно упрощается, и цель в том, что свёртки выберут из изображения признаки, определяющие выход сети. Действительно полезный метод в модели — это метод model.summary(). Он позволяет проинспектировать слои модели, и просмотреть весь путь, который проходит изображение через свёртки. Вот что он выводит. Эта классная табличка показывает нам слои и некоторые сведения о них, включая размерность выхода. Стоит обращать внимание на столбец с размерностью выхода. Когда вы первый раз смотрите на него, его вид может немного сбивать с толку и казаться ошибочным. Во-первых, размер у данных 28х28, так почему же на выходе имеем 26х26? Ключ к пониманию здесь — вспомнить, что фильтр имеет размер 3х3. Рассмотрим, что происходит, когда вы начинаете сканирование изображения, начиная с левого верхнего угла. Так, на примере этого изображения собаки (справа) вы можете увидеть фрагмент в верхнем левом углу, увеличенный до пикселов. Вы не можете посчитать фильтр для пиксела в левом верхнем углу, потому что у него нет никаких соседей выше или слева от него. Аналогичным образом, для следующего от него пиксела правее — это также не сработает, т.к. у нет соседей выше него. Поэтому логично, что первый пиксел, для которого можно сделать расчёт — вот этот, потому что у него есть все восемь соседей, необходимые фильтру. И если подумать, это означает, что нельзя использовать поле шириной в один пиксель по периметру всего изображения, и потому результат свёртки будет на 2 пиксела меньше по оси Х, и на 2 пиксела меньше по оси Y. Если ваш фильтр имеет размерность 5х5, то по тем же причинам, результат будет на 4 пиксела меньше по оси Х, и на 4 пиксела меньше по оси Y. Таким образом, в случае фильтра 3х3, выходным для изображения 28х28 — будет 26х26. Мы удалили тот один пиксель по X и по Y с каждой стороны. Далее идёт первый из MaxPooling слоёв. Вспомните, что мы определили его как 2х2, что превращает 4 пиксела в один по X и по Y. Так что теперь наш выход сократился с 26х26, до 13х13. Свёртки будут дальше работать с ним, и конечно, мы опять теряем поле в 1 пиксел, и размер понижается до 11х11, мы добавляем ещё один MaxPooling 2х2, чтобы сжать изображение, и так снижаем размер изображений до 5х5. Наша полносвязная нейронная сеть остаётся такой же, как прежде, но теперь она принимает на вход изображения размерностью 5х5 вместо картинок 28х28. Но запомните — это не просто единственное сжатое до 5х5 изображение — вместо оригинального 28х28. Это ряд свёрток для каждого изображения, которые мы определили. В нашем случае —их 64. Таким образом, у нас есть 64 новых изображения размерностью 5х5, которые подаются на вход. Развернув их, мы получим 25 пикселов * 64 изображения = 1600 пикселов. Как видите, в новом развернутом слое содержится 1600 элементов, в отличие от 784, как было ранее. Это число зависит от параметров, которые мы устанавливаем, определяя двумерные свёрточные слои. Позже, когда вы будете экспериментировать, то увидите, как повлияет подстановка других значений количества свёрток, и, в частности, увидите, что произойдёт, если подать на вход сети меньше чем 784 пикселов. Обучение должно пойти быстрее, но есть ли точка оптимума, где результат более точный? Давайте переключимся на workbook и попробуем сделать это самостоятельно.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# next code
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),

    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

Layer (type)                    Output Shape          Param # 
==========================================================
conv2d_12         (Conv2D)      (None, 26, 26, 64)    640
---------------------------------------------------------
max_pooling2d_12  (MaxPooling   (None, 13, 13, 64)    0
---------------------------------------------------------
conv2d_13         (Conv2D)      (None, 11, 11, 64)    36928
---------------------------------------------------------
max_pooling2d_13  (MaxPooling   (None, 5, 5, 64)      0
---------------------------------------------------------
flatten_5         (Flatten)     (None, 1600)          0
---------------------------------------------------------
dense_10          (Dense)       (None, 128)           204928
---------------------------------------------------------
dense_11          (Dense)       (None, 10)            1290
==========================================================
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

7(w3)-Getting hands-on, your first ConvNet: (15.MLg_1c)

(Практический опыт, ваша первая ConvNet)
You’ve now seen how to turn your Deep Neural Network into a Convolutional Neural Network by adding convolutional layers on top, and having the network train against the results of the convolutions instead of the raw pixels. In the next video, you’ll step through a workbook to see how this works…
---------------------------------------------------------------
Теперь вы увидели, как превратить вашу глубокую нейронную сеть в сверточную нейронную сеть, добавив сверху сверточные слои и заставив сеть обучаться на основе результатов сверток вместо необработанных пикселей. В следующем видео вы пройдете по книге, чтобы увидеть, как это работает…

8(w3)-video5: Improving the Fashion classifier with convolutions (15.MLg_1c)

(Улучшение классификатора моды с помощью сверток)
In the previous video, you looked at convolutions and got a glimpse for how they worked. By passing filters over an image to reduce the amount of information, they then allowed the neural network to effectively extract features that can distinguish one class of image from another. You also saw how pooling compresses the information to make it more manageable. This is a really nice way to improve our image recognition performance. Let's now look at it in action using a notebook.
Here's the same neural network that you used before for loading the set of images of clothing and then classifying them. *long pause* By the end of epoch five, you can see the loss is around 0.29, meaning, your accuracy is pretty good on the training data. It took just a few seconds to train, so that's not bad. With the test data as before and as expected, the losses a little higher and thus, the accuracy is a little lower. So now, you can see the code that adds convolutions and pooling. We're going to do two convolutional layers each with 64 convolution, and each followed by a max pooling layer. You can see that we defined our convolutions to be three-by-three and our pools to be two-by-two. Let's train. The first thing you'll notice is that the training is much slower. For every image, 64 convolutions are being tried, and then the image is compressed and then another 64 convolutions, and then it's compressed again, and then it's passed through the DNN, and that's for 60,000 images that this is happening on each epoch. So it might take a few minutes instead of a few seconds. Now that it's done, you can see that the loss has improved a little. In this case, it's brought our accuracy up a bit for both our test data and with our training data. That's pretty cool, right? Now, let's take a look at the code at the bottom of the notebook. Now, this is a really fun visualization of the journey of an image through the convolutions. First, I'll print out the first 100 test labels. The number nine as we saw earlier is a shoe or boots. I picked out a few instances of this whether the zero, the 23rd and the 28th labels are all nine. So let's take a look at their journey. The Keras API gives us each convolution and each pooling and each dense, etc. as a layer. So with the layers API, I can take a look at each layer's outputs, so I'll create a list of each layer's output. I can then treat each item in the layer as an individual activation model if I want to see the results of just that layer. Now, by looping through the layers, I can display the journey of the image through the first convolution and then the first pooling and then the second convolution and then the second pooling. Note how the size of the image is changing by looking at the axes. If I set the convolution number to one, we can see that it almost immediately detects the laces area as a common feature between the shoes. So, for example, if I change the third image to be one, which looks like a handbag, you'll see that it also has a bright line near the bottom that could look like the sole of the shoes, but by the time it gets through the convolutions, that's lost, and that area for the laces doesn't even show up at all. So this convolution definitely helps me separate issue from a handbag. Again, if I said it's a two, it appears to be trousers, but the feature that detected something that the shoes had in common fails again. Also, if I changed my third image back to that for shoe, but I tried a different convolution number, you'll see that for convolution two, it didn't really find any common features. To see commonality in a different image, try images two, three, and five. These all appear to be trousers. Convolutions two and four seem to detect this vertical feature as something they all have in common. If I again go to the list and find three labels that are the same, in this case six, I can see what they signify. When I run it, I can see that they appear to be shirts. Convolution four doesn't do a whole lot, so let's try five. We can kind of see that the color appears to light up in this case. Let's try convolution one. I don't know about you, but I can play with this all day. Then see what you do when you run it for yourself. When you're done playing, try tweaking the code with these suggestions, editing the convolutions, removing the final convolution, and adding more, etc. Also, in a previous exercise, you added a callback that finished training once the loss had a certain amount. So try to add that here. When you're done, we'll move to the next stage, and that's dealing with images that are larger and more complex than these ones. To see how convolutions can maybe detect features when they aren't always in the same place, like they would be in these tightly controlled 28 by 28 images.
---------------------------------------------------------------
В предыдущем видео вы посмотрели на свёртки и получили некоторое представление о том, как они работают. Проходя фильтрами по изображению, чтобы уменьшить объём информации, мы позволяем нейронной сети эффективно извлечь признаки, которые отличают один класс изображений от другого. Вы также видели, как пулинг сжимает информацию, чтобы облегчить обработку. Это действительно хороший способ улучшить производительность нашего распознавания изображения. Давайте теперь посмотрим на это в действии, в блокноте. Здесь та же самая нейронная сеть, которую вы использовали ранее, загружая набор изображений одежды и классифицируя их. К концу пятой эпохи вы видите, что потери в районе 0.29, то есть, ваша точность на обучающем наборе довольна высока. Обучение заняло всего несколько секунд, так что результат неплохой. На тестовых данных, как и раньше, и как и ожидалось, потерь немного больше, и соответственно, точность немного ниже. Теперь вы можете видеть код, который добавляет свёртки и пулинг. Мы сделаем 2 свёрточных слоя, содержащих по 64 свёртки каждый, за каждым из них следует слой MaxPooling. Как вы видите, мы определили наши свёртки размерностью 3х3, а наши пулы размером 2х2. Давайте обучим. Первое, что бросится в глаза — это что обучение стало гораздо медленнее. К каждому изображению применяются по 64 свёртки, затем изображение сжимается, а затем следующие 64 свёртки, и затем опять сжимается, и лишь потом пропускается через полносвязную сеть (DNN). И это всё выполняется каждую эпоху для 60,000 изображений. Так что это может занять несколько минут вместо нескольких секунд. Теперь, когда всё готово, вы можете увидеть, что потери немного улучшились. В нашем случае, это чуть повысило нашу точность на обоих наборах: на тестовых данных и обучающих данных. Довольно неплохо, верно? Теперь давайте взглянем на код в нижней части блокнота. Это любопытная визуализация прохождения изображения через свёртки. Для начала я выведу первые 100 тестовых меток. Число 9, как мы видели ранее, соответствует обуви или ботинкам. Я выбрал несколько примеров: нулевую метку, 23ю и 28ю — все со значением 9. Давайте взглянем на их путь по сети. Keras API представляет нам каждую свёртку, каждый пулинг и каждую полносвязную часть и т.д. как отдельный слой. Поэтому используя API для слоёв, я могу посмотреть выходы каждого слоя, т.е. я создам список выходов каждого из слоёв. Затем я могу рассматривать каждый элемент в слое как отдельную модель активации, в случае если я захочу увидеть результаты только этого слоя. Теперь, перечисляя слои, я могу отобразить прохождение изображения через первую свёртку, и первый пулинг, а затем — через вторую свёртку и второй пулинг. Обратите внимание, следя за осями, как меняется размер изображения. Если я установлю номер свёртки CONVOLUTION_NUMBER =1, то мы можем увидеть, что она почти сразу обнаруживает область шнурков как общий признак для всей обуви. Если, например, я изменю третье изображение THIRD_IMAGE=1, которое похоже на сумочку, то вы увидите, что оно также имеет светлую полоску снизу, которая могла бы выглядеть как подошва обуви. Но пока изображение проходит через свёртки, она исчезает, а эта область для шнурков не появляется вовсе. Так что эта свертка определенно помогает мне отличить обувь от сумочки. Опять же, если бы я сказал, что THIRD_IMAGE=2, на котором, похоже, брюки, но признак, выявляющий что-то, что свойственно для обуви, — опять не срабатывает. Также, если бы я вернул моё THIRD_IMAGE обратно на обувь, но попробовал бы другой CONVOLUTION_NUMBER, то вы бы увидели, что для свёртки номер 2 никаких общих признаков не было найдено. Чтобы увидеть сходство на другом изображении, попробуйте изображения 2, 3 и 5. Все они являются брюками. Свёртки 2 и 4, похоже, определяют вертикальный признак как нечто общее между изображениями. Если я снова вернусь к списку и найду 3 одинаковых метки, в данном случае, с номером 6, то смогу увидеть, что они обозначают. Когда я выполню это, увижу, что они представляют из себя рубашки. Свёртка номер 4 особо ничего не делает, поэтому давайте попробуем пятую. Мы видим, что в данном случае становится важен цвет. Давайте попробуем свертку номер 1. Не знаю как вы, но я могу играться с этим весь день. Посмотрите, что будет, когда будете запускать у себя. Когда вы наиграетесь, попробуйте покрутить код, пользуясь следующими рекомендациями: поизменяйте свёртки, удалите последнюю свёртку и добавьте больше и т.д. Также в предыдущем упражнении вы добавили обратный вызов, который завершал обучение, как только потеря достигала определённого значения. Попробуйте добавить его и здесь. Когда вы закончите, мы перейдем к следующему этапу, где мы будем иметь дело с изображениями, которые больше по размеру и более сложные, чем эти, — чтобы увидеть, смогут ли свёртки определить признаки, которые не всегда располагаются на том же самом месте, как это было в прежних жестко подконтрольных изображениях 28х28 .

9(w3)-Try it for yourself (Lab 1): (15.MLg_1c)

Here is the notebook that Laurence was using in that screencast. If you're running this in Colab, the GPU runtime has already been pre-selected for you to make the training run faster.
Work through it, and try some of the exercises at the bottom. It's really worth spending a bit of time on these because, as before, they'll really help you by seeing the impact of small changes to various parameters in the code. You should spend at least 1 hour on this today!
Once you’re done, go onto the next video and take a look at some code to build a convolution yourself to visualize how it works!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W3/ungraded_labs/C1_W3_Lab_1_improving_accuracy_using_convolutions.ipynb
---------------------------------------------------------------
Вот блокнот, который Лоуренс использовал в этом скринкасте. Если вы запускаете это в Colab, среда выполнения GPU уже была предварительно выбрана для ускорения обучения.
Проработайте его и попробуйте некоторые из упражнений внизу. На них действительно стоит потратить немного времени, потому что, как и прежде, они действительно помогут вам, увидев влияние небольших изменений на различные параметры в коде. Вы должны потратить на это как минимум 1 час сегодня!
Как только вы закончите, перейдите к следующему видео и взгляните на код, чтобы самостоятельно создать свертку, чтобы визуализировать, как она работает!
---------------------------------------------------------------
Convolutional Neural Network:
(Сверточная нейронная сеть)
Convolutional Neural Network
In the model above, your accuracy will probably be about 89% on training and 87% on validation. Not bad. But how do you make that even better? One way is to use something called convolutions. We're not going into the details of convolutions in this notebook (please see resources in the classroom), but the ultimate concept is that they narrow down the content of the image to focus on specific parts and this will likely improve the model accuracy.
If you've ever done image processing using a filter (like this, then convolutions will look very familiar. In short, you take an array (usually 3x3 or 5x5) and scan it over the entire image. By changing the underlying pixels based on the formula within that matrix, you can do things like edge detection. So, for example, if you look at the above link, you'll see a 3x3 matrix that is defined for edge detection where the middle cell is 8, and all of its neighbors are -1. In this case, for each pixel, you would multiply its value by 8, then subtract the value of each neighbor. Do this for every pixel, and you'll end up with a new image that has the edges enhanced.
This is perfect for computer vision because it often highlights features that distinguish one item from another. Moreover, the amount of information needed is then much less because you'll just train on the highlighted features.
That's the concept of Convolutional Neural Networks. Add some layers to do convolution before you have the dense layers, and then the information going to the dense layers is more focused and possibly more accurate.
---------------------------------------------------------------
В приведенной выше модели ваша точность, вероятно, будет около 89% при обучении и 87% при проверке. Неплохо. Но как сделать это еще лучше? Один из способов — использовать так называемые свертки. Мы не будем вдаваться в детали сверток в этой записной книжке (см. ресурсы в классе), но окончательная концепция заключается в том, что они сужают содержимое изображения, чтобы сосредоточиться на определенных частях, и это, вероятно, повысит точность модели.
Если вы когда-либо выполняли обработку изображения с помощью фильтра (подобного этому), то свертки будут выглядеть очень знакомо. Короче говоря, вы берете массив (обычно 3x3 или 5x5) и сканируете его по всему изображению. Изменяя базовые пиксели на основе формулу в этой матрице, вы можете делать такие вещи, как обнаружение края.Так, например, если вы посмотрите на приведенную выше ссылку, вы увидите матрицу 3x3, которая определена для обнаружения края, где средняя ячейка равна 8, а все его соседи равны -1. В этом случае для каждого пикселя вы должны умножить его значение на 8, а затем вычесть значение каждого соседа. Сделайте это для каждого пикселя, и вы получите новое изображение с краями повышенная.
Это идеально подходит для компьютерного зрения, поскольку часто выделяет функции, отличающие один элемент от другого. Более того, объем необходимой информации в таком случае будет намного меньше, потому что вы просто будете тренироваться на выделенных функциях.
Это концепция сверточных нейронных сетей. Добавьте несколько слоев для выполнения свертки, прежде чем вы получите плотные слои, и тогда информация, поступающая в плотные слои, будет более целенаправленной и, возможно, более точной.
---------------------------------------------------------------
Look at the code again, and see, step by step how the convolutions were built. Instead of the input layer at the top, you added a Conv2D layer. The parameters are:
1. The number of convolutions you want to generate. The value here is purely arbitrary but it's good to use powers of 2 starting from 32.
2. The size of the Convolution. In this case, a 3x3 grid.
3. The activation function to use. In this case, you used a ReLU, which you might recall is the equivalent of returning x when x>0, else return 0.
4. In the first layer, the shape of the input data.
---------------------------------------------------------------
Посмотрите еще раз на код и посмотрите, шаг за шагом, как строились свертки. Вместо входного слоя вверху вы добавили слой Conv2D. Параметры:
1. Количество сверток, которые вы хотите сгенерировать. Значение здесь чисто произвольное, но лучше использовать степени двойки, начиная с 32.
2. Размер свертки. В данном случае сетка 3х3.
3. Функция активации для использования. В этом случае вы использовали ReLU, который, как вы, возможно, помните, эквивалентен возврату x, когда x>0, иначе возвращает 0.
4. В первом слое форма входных данных.

You'll follow the convolution with a MaxPool2D layer which is designed to compress the image, while maintaining the content of the features that were highlighted by the convlution. By specifying (2,2) for the MaxPooling, the effect is to quarter the size of the image. Without going into too much detail here, the idea is that it creates a 2x2 array of pixels, and picks the biggest one. Thus, it turns 4 pixels into 1. It repeats this across the image, and in doing so, it halves both the number of horizontal and vertical pixels, effectively reducing the image to 25% of the original image.
You can call model.summary() to see the size and shape of the network, and you'll notice that after every max pooling layer, the image size is reduced in this way.
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
---------------------------------------------------------------
Вы проследите за сверткой со слоем MaxPool2D, который предназначен для сжатия изображения, сохраняя при этом содержимое функций, выделенных сверткой. При указании (2,2) для MaxPooling размер изображения увеличивается в четыре раза. Не вдаваясь в подробности, идея состоит в том, что он создает массив пикселей 2x2 и выбирает самый большой из них. Таким образом, он превращает 4 пикселя в 1. Это повторяется по всему изображению, и при этом количество пикселей по горизонтали и по вертикали уменьшается вдвое, эффективно уменьшая изображение до 25% от исходного изображения.
Вы можете вызвать model.summary(), чтобы увидеть размер и форму сети, и вы заметите, что после каждого максимального слоя пула размер изображения уменьшается в этом
---------------------------------------------------------------
Then you added another convolution and flattened the output. (Затем вы добавили еще одну свертку и сгладили вывод.)
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2)
tf.keras.layers.Flatten(),
---------------------------------------------------------------
After this, you'll just have the same DNN structure as the non convolutional version. The same 128 dense layers, and 10 output layers as in the pre-convolution example:
(После этого у вас будет та же структура DNN, что и в не сверточной версии. Те же 128 плотных слоев и 10 выходных слоев, что и в примере до свертки:)
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')

=======

7(w3)-Getting hands-on, your first ConvNet: (15.MLg_1c)

(Практический опыт, ваша первая ConvNet)
You’ve now seen how to turn your Deep Neural Network into a Convolutional Neural Network by adding convolutional layers on top, and having the network train against the results of the convolutions instead of the raw pixels. In the next video, you’ll step through a workbook to see how this works…
---------------------------------------------------------------
Теперь вы увидели, как превратить вашу глубокую нейронную сеть в сверточную нейронную сеть, добавив сверху сверточные слои и заставив сеть обучаться на основе результатов сверток вместо необработанных пикселей. В следующем видео вы пройдете по книге, чтобы увидеть, как это работает…

8(w3)-video5: Improving the Fashion classifier with convolutions (15.MLg_1c)

(Улучшение классификатора моды с помощью сверток)
In the previous video, you looked at convolutions and got a glimpse for how they worked. By passing filters over an image to reduce the amount of information, they then allowed the neural network to effectively extract features that can distinguish one class of image from another. You also saw how pooling compresses the information to make it more manageable. This is a really nice way to improve our image recognition performance. Let's now look at it in action using a notebook.
Here's the same neural network that you used before for loading the set of images of clothing and then classifying them. *long pause* By the end of epoch five, you can see the loss is around 0.29, meaning, your accuracy is pretty good on the training data. It took just a few seconds to train, so that's not bad. With the test data as before and as expected, the losses a little higher and thus, the accuracy is a little lower. So now, you can see the code that adds convolutions and pooling. We're going to do two convolutional layers each with 64 convolution, and each followed by a max pooling layer. You can see that we defined our convolutions to be three-by-three and our pools to be two-by-two. Let's train. The first thing you'll notice is that the training is much slower. For every image, 64 convolutions are being tried, and then the image is compressed and then another 64 convolutions, and then it's compressed again, and then it's passed through the DNN, and that's for 60,000 images that this is happening on each epoch. So it might take a few minutes instead of a few seconds. Now that it's done, you can see that the loss has improved a little. In this case, it's brought our accuracy up a bit for both our test data and with our training data. That's pretty cool, right? Now, let's take a look at the code at the bottom of the notebook. Now, this is a really fun visualization of the journey of an image through the convolutions. First, I'll print out the first 100 test labels. The number nine as we saw earlier is a shoe or boots. I picked out a few instances of this whether the zero, the 23rd and the 28th labels are all nine. So let's take a look at their journey. The Keras API gives us each convolution and each pooling and each dense, etc. as a layer. So with the layers API, I can take a look at each layer's outputs, so I'll create a list of each layer's output. I can then treat each item in the layer as an individual activation model if I want to see the results of just that layer. Now, by looping through the layers, I can display the journey of the image through the first convolution and then the first pooling and then the second convolution and then the second pooling. Note how the size of the image is changing by looking at the axes. If I set the convolution number to one, we can see that it almost immediately detects the laces area as a common feature between the shoes. So, for example, if I change the third image to be one, which looks like a handbag, you'll see that it also has a bright line near the bottom that could look like the sole of the shoes, but by the time it gets through the convolutions, that's lost, and that area for the laces doesn't even show up at all. So this convolution definitely helps me separate issue from a handbag. Again, if I said it's a two, it appears to be trousers, but the feature that detected something that the shoes had in common fails again. Also, if I changed my third image back to that for shoe, but I tried a different convolution number, you'll see that for convolution two, it didn't really find any common features. To see commonality in a different image, try images two, three, and five. These all appear to be trousers. Convolutions two and four seem to detect this vertical feature as something they all have in common. If I again go to the list and find three labels that are the same, in this case six, I can see what they signify. When I run it, I can see that they appear to be shirts. Convolution four doesn't do a whole lot, so let's try five. We can kind of see that the color appears to light up in this case. Let's try convolution one. I don't know about you, but I can play with this all day. Then see what you do when you run it for yourself. When you're done playing, try tweaking the code with these suggestions, editing the convolutions, removing the final convolution, and adding more, etc. Also, in a previous exercise, you added a callback that finished training once the loss had a certain amount. So try to add that here. When you're done, we'll move to the next stage, and that's dealing with images that are larger and more complex than these ones. To see how convolutions can maybe detect features when they aren't always in the same place, like they would be in these tightly controlled 28 by 28 images.
---------------------------------------------------------------
В предыдущем видео вы посмотрели на свёртки и получили некоторое представление о том, как они работают. Проходя фильтрами по изображению, чтобы уменьшить объём информации, мы позволяем нейронной сети эффективно извлечь признаки, которые отличают один класс изображений от другого. Вы также видели, как пулинг сжимает информацию, чтобы облегчить обработку. Это действительно хороший способ улучшить производительность нашего распознавания изображения. Давайте теперь посмотрим на это в действии, в блокноте. Здесь та же самая нейронная сеть, которую вы использовали ранее, загружая набор изображений одежды и классифицируя их. К концу пятой эпохи вы видите, что потери в районе 0.29, то есть, ваша точность на обучающем наборе довольна высока. Обучение заняло всего несколько секунд, так что результат неплохой. На тестовых данных, как и раньше, и как и ожидалось, потерь немного больше, и соответственно, точность немного ниже. Теперь вы можете видеть код, который добавляет свёртки и пулинг. Мы сделаем 2 свёрточных слоя, содержащих по 64 свёртки каждый, за каждым из них следует слой MaxPooling. Как вы видите, мы определили наши свёртки размерностью 3х3, а наши пулы размером 2х2. Давайте обучим. Первое, что бросится в глаза — это что обучение стало гораздо медленнее. К каждому изображению применяются по 64 свёртки, затем изображение сжимается, а затем следующие 64 свёртки, и затем опять сжимается, и лишь потом пропускается через полносвязную сеть (DNN). И это всё выполняется каждую эпоху для 60,000 изображений. Так что это может занять несколько минут вместо нескольких секунд. Теперь, когда всё готово, вы можете увидеть, что потери немного улучшились. В нашем случае, это чуть повысило нашу точность на обоих наборах: на тестовых данных и обучающих данных. Довольно неплохо, верно? Теперь давайте взглянем на код в нижней части блокнота. Это любопытная визуализация прохождения изображения через свёртки. Для начала я выведу первые 100 тестовых меток. Число 9, как мы видели ранее, соответствует обуви или ботинкам. Я выбрал несколько примеров: нулевую метку, 23ю и 28ю — все со значением 9. Давайте взглянем на их путь по сети. Keras API представляет нам каждую свёртку, каждый пулинг и каждую полносвязную часть и т.д. как отдельный слой. Поэтому используя API для слоёв, я могу посмотреть выходы каждого слоя, т.е. я создам список выходов каждого из слоёв. Затем я могу рассматривать каждый элемент в слое как отдельную модель активации, в случае если я захочу увидеть результаты только этого слоя. Теперь, перечисляя слои, я могу отобразить прохождение изображения через первую свёртку, и первый пулинг, а затем — через вторую свёртку и второй пулинг. Обратите внимание, следя за осями, как меняется размер изображения. Если я установлю номер свёртки CONVOLUTION_NUMBER =1, то мы можем увидеть, что она почти сразу обнаруживает область шнурков как общий признак для всей обуви. Если, например, я изменю третье изображение THIRD_IMAGE=1, которое похоже на сумочку, то вы увидите, что оно также имеет светлую полоску снизу, которая могла бы выглядеть как подошва обуви. Но пока изображение проходит через свёртки, она исчезает, а эта область для шнурков не появляется вовсе. Так что эта свертка определенно помогает мне отличить обувь от сумочки. Опять же, если бы я сказал, что THIRD_IMAGE=2, на котором, похоже, брюки, но признак, выявляющий что-то, что свойственно для обуви, — опять не срабатывает. Также, если бы я вернул моё THIRD_IMAGE обратно на обувь, но попробовал бы другой CONVOLUTION_NUMBER, то вы бы увидели, что для свёртки номер 2 никаких общих признаков не было найдено. Чтобы увидеть сходство на другом изображении, попробуйте изображения 2, 3 и 5. Все они являются брюками. Свёртки 2 и 4, похоже, определяют вертикальный признак как нечто общее между изображениями. Если я снова вернусь к списку и найду 3 одинаковых метки, в данном случае, с номером 6, то смогу увидеть, что они обозначают. Когда я выполню это, увижу, что они представляют из себя рубашки. Свёртка номер 4 особо ничего не делает, поэтому давайте попробуем пятую. Мы видим, что в данном случае становится важен цвет. Давайте попробуем свертку номер 1. Не знаю как вы, но я могу играться с этим весь день. Посмотрите, что будет, когда будете запускать у себя. Когда вы наиграетесь, попробуйте покрутить код, пользуясь следующими рекомендациями: поизменяйте свёртки, удалите последнюю свёртку и добавьте больше и т.д. Также в предыдущем упражнении вы добавили обратный вызов, который завершал обучение, как только потеря достигала определённого значения. Попробуйте добавить его и здесь. Когда вы закончите, мы перейдем к следующему этапу, где мы будем иметь дело с изображениями, которые больше по размеру и более сложные, чем эти, — чтобы увидеть, смогут ли свёртки определить признаки, которые не всегда располагаются на том же самом месте, как это было в прежних жестко подконтрольных изображениях 28х28 .

9(w3)-Try it for yourself (Lab 1): (15.MLg_1c)

Here is the notebook that Laurence was using in that screencast. If you're running this in Colab, the GPU runtime has already been pre-selected for you to make the training run faster.
Work through it, and try some of the exercises at the bottom. It's really worth spending a bit of time on these because, as before, they'll really help you by seeing the impact of small changes to various parameters in the code. You should spend at least 1 hour on this today!
Once you’re done, go onto the next video and take a look at some code to build a convolution yourself to visualize how it works!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W3/ungraded_labs/C1_W3_Lab_1_improving_accuracy_using_convolutions.ipynb
---------------------------------------------------------------
Вот блокнот, который Лоуренс использовал в этом скринкасте. Если вы запускаете это в Colab, среда выполнения GPU уже была предварительно выбрана для ускорения обучения.
Проработайте его и попробуйте некоторые из упражнений внизу. На них действительно стоит потратить немного времени, потому что, как и прежде, они действительно помогут вам, увидев влияние небольших изменений на различные параметры в коде. Вы должны потратить на это как минимум 1 час сегодня!
Как только вы закончите, перейдите к следующему видео и взгляните на код, чтобы самостоятельно создать свертку, чтобы визуализировать, как она работает!
---------------------------------------------------------------
Convolutional Neural Network:
(Сверточная нейронная сеть)
Convolutional Neural Network
In the model above, your accuracy will probably be about 89% on training and 87% on validation. Not bad. But how do you make that even better? One way is to use something called convolutions. We're not going into the details of convolutions in this notebook (please see resources in the classroom), but the ultimate concept is that they narrow down the content of the image to focus on specific parts and this will likely improve the model accuracy.
If you've ever done image processing using a filter (like this, then convolutions will look very familiar. In short, you take an array (usually 3x3 or 5x5) and scan it over the entire image. By changing the underlying pixels based on the formula within that matrix, you can do things like edge detection. So, for example, if you look at the above link, you'll see a 3x3 matrix that is defined for edge detection where the middle cell is 8, and all of its neighbors are -1. In this case, for each pixel, you would multiply its value by 8, then subtract the value of each neighbor. Do this for every pixel, and you'll end up with a new image that has the edges enhanced.
This is perfect for computer vision because it often highlights features that distinguish one item from another. Moreover, the amount of information needed is then much less because you'll just train on the highlighted features.
That's the concept of Convolutional Neural Networks. Add some layers to do convolution before you have the dense layers, and then the information going to the dense layers is more focused and possibly more accurate.
---------------------------------------------------------------
В приведенной выше модели ваша точность, вероятно, будет около 89% при обучении и 87% при проверке. Неплохо. Но как сделать это еще лучше? Один из способов — использовать так называемые свертки. Мы не будем вдаваться в детали сверток в этой записной книжке (см. ресурсы в классе), но окончательная концепция заключается в том, что они сужают содержимое изображения, чтобы сосредоточиться на определенных частях, и это, вероятно, повысит точность модели.
Если вы когда-либо выполняли обработку изображения с помощью фильтра (подобного этому), то свертки будут выглядеть очень знакомо. Короче говоря, вы берете массив (обычно 3x3 или 5x5) и сканируете его по всему изображению. Изменяя базовые пиксели на основе формулу в этой матрице, вы можете делать такие вещи, как обнаружение края.Так, например, если вы посмотрите на приведенную выше ссылку, вы увидите матрицу 3x3, которая определена для обнаружения края, где средняя ячейка равна 8, а все его соседи равны -1. В этом случае для каждого пикселя вы должны умножить его значение на 8, а затем вычесть значение каждого соседа. Сделайте это для каждого пикселя, и вы получите новое изображение с краями повышенная.
Это идеально подходит для компьютерного зрения, поскольку часто выделяет функции, отличающие один элемент от другого. Более того, объем необходимой информации в таком случае будет намного меньше, потому что вы просто будете тренироваться на выделенных функциях.
Это концепция сверточных нейронных сетей. Добавьте несколько слоев для выполнения свертки, прежде чем вы получите плотные слои, и тогда информация, поступающая в плотные слои, будет более целенаправленной и, возможно, более точной.
---------------------------------------------------------------
Look at the code again, and see, step by step how the convolutions were built. Instead of the input layer at the top, you added a Conv2D layer. The parameters are:
1. The number of convolutions you want to generate. The value here is purely arbitrary but it's good to use powers of 2 starting from 32.
2. The size of the Convolution. In this case, a 3x3 grid.
3. The activation function to use. In this case, you used a ReLU, which you might recall is the equivalent of returning x when x>0, else return 0.
4. In the first layer, the shape of the input data.
---------------------------------------------------------------
Посмотрите еще раз на код и посмотрите, шаг за шагом, как строились свертки. Вместо входного слоя вверху вы добавили слой Conv2D. Параметры:
1. Количество сверток, которые вы хотите сгенерировать. Значение здесь чисто произвольное, но лучше использовать степени двойки, начиная с 32.
2. Размер свертки. В данном случае сетка 3х3.
3. Функция активации для использования. В этом случае вы использовали ReLU, который, как вы, возможно, помните, эквивалентен возврату x, когда x>0, иначе возвращает 0.
4. В первом слое форма входных данных.

You'll follow the convolution with a MaxPool2D layer which is designed to compress the image, while maintaining the content of the features that were highlighted by the convlution. By specifying (2,2) for the MaxPooling, the effect is to quarter the size of the image. Without going into too much detail here, the idea is that it creates a 2x2 array of pixels, and picks the biggest one. Thus, it turns 4 pixels into 1. It repeats this across the image, and in doing so, it halves both the number of horizontal and vertical pixels, effectively reducing the image to 25% of the original image.
You can call model.summary() to see the size and shape of the network, and you'll notice that after every max pooling layer, the image size is reduced in this way.
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
---------------------------------------------------------------
Вы проследите за сверткой со слоем MaxPool2D, который предназначен для сжатия изображения, сохраняя при этом содержимое функций, выделенных сверткой. При указании (2,2) для MaxPooling размер изображения увеличивается в четыре раза. Не вдаваясь в подробности, идея состоит в том, что он создает массив пикселей 2x2 и выбирает самый большой из них. Таким образом, он превращает 4 пикселя в 1. Это повторяется по всему изображению, и при этом количество пикселей по горизонтали и по вертикали уменьшается вдвое, эффективно уменьшая изображение до 25% от исходного изображения.
Вы можете вызвать model.summary(), чтобы увидеть размер и форму сети, и вы заметите, что после каждого максимального слоя пула размер изображения уменьшается в этом
---------------------------------------------------------------
Then you added another convolution and flattened the output. (Затем вы добавили еще одну свертку и сгладили вывод.)
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2)
tf.keras.layers.Flatten(),
---------------------------------------------------------------
After this, you'll just have the same DNN structure as the non convolutional version. The same 128 dense layers, and 10 output layers as in the pre-convolution example:
(После этого у вас будет та же структура DNN, что и в не сверточной версии. Те же 128 плотных слоев и 10 выходных слоев, что и в примере до свертки:)
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# Define the model
model = tf.keras.models.Sequential([
                                                         
  # Add convolutions and max pooling
  tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
  tf.keras.layers.MaxPooling2D(2, 2),
  tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
  tf.keras.layers.MaxPooling2D(2,2),

  # Add the same layers as before
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(10, activation='softmax')
])

# Print the model summary
model.summary()

# Use same settings
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
print(f'\nMODEL TRAINING:')
model.fit(training_images, training_labels, epochs=5)

# Evaluate on the test set
print(f'\nMODEL EVALUATION:')
test_loss = model.evaluate(test_images, test_labels)
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

10(w3)-video6: Walking through convolutions (15.MLg_1c)

(Прогулка по сверткам, извилинам)
In the previous lessons, you saw the impacts that convolutions and pooling had on your networks efficiency and learning, but a lot of that was theoretical in nature. So I thought it'd be interesting to hack some code together to show how a convolution actually works. We'll also create a little pooling algorithm, so you can visualize its impact. There's a notebook that you can play with too, and I'll step through that here. Here's the notebook for playing with convolutions. So first, we'll set up our inputs and in particular, import the misc library from SciPy. Now, this is a nice shortcut for us because misc.ascent returns a nice image that we can play with, and we don't have to worry about managing our own. Matplotlib contains the code for drawing an image and it will render it right in the browser with Colab. Here, we can see the ascent image from SciPy. Next up, we'll take a copy of the image, and we'll add it with our homemade convolutions, and we'll create variables to keep track of the x and y dimensions of the image. So we can see here that it's a 512 by 512 image. So now, let's create a convolution as a three by three array. We'll load it with values that are pretty good for detecting sharp edges first. Here's where we'll create the convolution. We iterate over the image, leaving a one pixel margin. You'll see that the loop starts at one and not zero, and it ends at size x minus one and size y minus one. In the loop, it will then calculate the convolution value by looking at the pixel and its neighbors, and then by multiplying them out by the values determined by the filter, before finally summing it all up. Let's run it. It takes just a few seconds, so when it's done, let's draw the results. We can see that only certain features made it through the filter. I've provided a couple more filters, so let's try them. This first one is really great at spotting vertical lines. So when I run it, and plot the results, we can see that the vertical lines in the image made it through. It's really cool because they're not just straight up and down, they are vertical in perspective within the perspective of the image itself. Similarly, this filter works well for horizontal lines. So when I run it, and then plot the results, we can see that a lot of the horizontal lines made it through. Now, let's take a look at pooling, and in this case, Max pooling, which takes pixels in chunks of four and only passes through the biggest value. I run the code and then render the output. We can see that the features of the image are maintained, but look closely at the axes, and we can see that the size has been halved from the 500's to the 250's. For fun, we can try the other filter, run it, and then compare the convolution with its pooled version. Again, we can see that the features have not just been maintained, they may have also been emphasized a bit. So that's how convolutions work. Under the hood, TensorFlow is trying different filters on your image and learning which ones work when looking at the training data. As a result, when it works, you'll have greatly reduced information passing through the network, but because it isolates and identifies features, you can also get increased accuracy.
Have a play with the filters in this workbook and see if you can come up with some interesting effects of your own.
---------------------------------------------------------------
На предыдущих занятиях вы видели, как повлияли свёртки и пулинг на эффективность сети и обучение, но многое из этого имело теоретический характер. Поэтому я подумал, что было бы интересно нам вместе поиграть с кодом, чтобы показать, как на самом деле работают свертки. Мы также создадим небольшой алгоритм пулинга, так что вы сможете увидеть его воздействие. Вы тоже сможете поиграть с блокнотом, а я сейчас пройдусь по нему пошагово. Вот блокнот, чтобы поиграться со свёртками. Здесь используются несколько Python-библиотек, с которыми вы, возможно незнакомы — например, cv2. В нём также используется Matplotlib, которую мы использовали ранее. Если вы не использовали их — не страшно, они достаточно интуитивно понятны для выполнения этой задачи, и их очень легко изучить. Итак, сначала мы настроим все импорты, в частности, импортируем библиотеку misc из SciPy. Это здорово сэкономит нам время, поскольку misc.ascent() возвращает хорошее изображение, с которым можно играться, и нам не придётся заниматься подготовкой своего. Библиотека Matplotlib содержит код для отрисовки изображений, и она отрисует его прямо в браузере с Colab. Здесь мы видим изображение ascent из SciPy. Следующим шагом мы сделаем копию изображения, дополним его нашими самодельными свёртками, и создадим переменные для отслеживания размеров изображения x и y. Мы видим, что это изображение имеет размер 512х512. Итак, давайте создадим свертку как массив 3х3. Мы заполняем его значениями, хорошо подходящими для обнаружения резких краёв. А здесь мы будем создавать свертки. Мы итерируемся по всему изображению, оставляя поля в 1 пиксел. Вы видите, что цикл начинается с 1, а не с 0, а завершается на size_x-1, и size_y-1. В этом цикле вычисляется значение свёртки: берутся значения пикселя и его соседей, и умножаются на значения, заданные фильтром, и результаты затем суммируются. Давайте запустим этот код. Это займёт всего несколько секунд, и когда будет готово — отобразим результаты. Мы видим, что лишь определённые признаки прошли сквозь фильтр. У меня есть ещё парочка фильтров, так что давайте попробуем их. Этот фильтр отлично справляется с выявлением вертикальных линий. Поэтому, когда я запущу его и отображу результаты, мы увидим, что вертикальные линии на изображении прошли через него. Это действительно здорово, потому что они не просто идут сверху вниз, а они вертикальны в перспективе, внутри перспективы самого изображения. Подобным образом, вот этот фильтр хорошо работает для горизонтальных линий. И когда я запущу его, и затем выведу результаты, мы видим, что многие горизонтальные линии прошли через него. Теперь давайте посмотрим на пулинг, а в нашем случае, это MaxPooling, при котором пикселы берутся порциями по 4, а пропускаются только наибольшие значения. Я запускаю код, и выводится результат. Мы видим, что признаки на изображении сохранились, но посмотрев внимательно на оси, мы видим, что размер уменьшился наполовину с 500 до 250. Ради забавы мы можем попробовать другой фильтр, выполнить его и затем сравнить свёртку с результатом пулинга над ней. Опять же мы видим, что признаки не просто сохранились, они также стали немного более выраженными. Вот так работают свёртки. Под капотом TensorFlow пробует различные фильтры на вашем изображении и изучает, какие из них работают, глядя на учебные данные. В результате, при его работе сильно сократится объём информации, пропускаемой через сеть. Однако т.к. это изолирует и выделяет признаки, можно также получить прирост точности. Поиграйтесь с фильтрами в этой рабочей тетради, и посмотрите, найдёте ли вы самостоятельно какие-нибудь интересные эффекты.

10(w3)- Experiment with filters and pools (Lab 2): (15.MLg_1c)

( Экспериментируйте с фильтрами и пулами)
Here is the notebook to try some convolutions. Let us know if you come up with any interesting filters of your own!
As before, spend a little time playing with this notebook. Try different filters, and research different filter types. There's some fun information about them here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W3/ungraded_labs/C1_W3_Lab_2_exploring_convolutions.ipynb
https://lodev.org/cgtutor/filtering.html
---------------------------------------------------------------
Вот блокнот, чтобы попробовать некоторые извилины. Дайте нам знать, если вы придумаете какие-нибудь интересные фильтры!
Как и прежде, потратьте немного времени, играя с этим блокнотом. Попробуйте разные фильтры и исследуйте разные типы фильтров. Есть забавная информация о них здесь.

11(w3)- Week 3 Quiz: (15.MLg_1c)

1) How do Convolutions improve image recognition?:
1.They make the image clearer
2. They make the image smaller
3. They make processing of images faster
4. They isolate features in images (+)
2) What does the Pooling technique do to the images?:
1. Combines them
2. Makes them sharper
3. Isolates features in them
4. Reduces information in them while maintaining some features (+)
3) True or False. If you pass a 28x28 image through a 3x3 filter the output will be 26x26?:
True (+)
4) After max pooling a 26x26 image with a 2x2 filter, the output will be 56x56?:
False (+)
5) How does using Convolutions in out Deep neural network impact training?:
1. It does not affect training
2. Its impact will depend on other factors (+)
3. It makes it faster
4. It makes is slower

11(w3)- Lecture Notes Week 3: (15.MLg_1c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах Эти слайды распространяются по лицензии Creative Commons.
DeepLearning.AI делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

12(w3)-Weekly Assignment: (15.MLg_1c)

Improve MNIST with convolutions (Улучшить MNIST с помощью сверток)
Ok, now it’s time for this week’s assignment. In the class, you learned how to enhance the Fashion MNIST neural network with convolutions to make it more accurate. Now it’s time to revisit the handwriting MNIST dataset from last week, and see if you can enhance it with convolutions.
To submit your Jupyter Notebook for grading, please click the Submit Assignment button while in the notebook.
---------------------------------------------------------------
Хорошо, теперь пришло время для задания этой недели. На занятии вы узнали, как улучшить нейронную сеть Fashion MNIST с помощью сверток, чтобы сделать ее более точной. Теперь пришло время вернуться к набору данных рукописного ввода MNIST с прошлой недели и посмотреть, сможете ли вы улучшить его с помощью сверток.
Чтобы отправить блокнот Jupyter на оценку, нажмите кнопку «Отправить задание» в блокноте.
---------------------------------------------------------------
IMPORTANT FOR SUCCESSFUL GRADING:
- Don't forget to save your notebook before submitting!
- Don't delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не забудьте сохранить блокнот перед отправкой!
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

NEXT week_4 (15.MLg_1c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/:

(w4) Using Real-world Images (15.MLg_1c)

(Использование изображений реального мира)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 27 minutes
Self-study: 2,23 hour
Graded tasks (Tasks to be assessed): 2

(w4) Introduction: (15.MLg_1c)

Last week you saw how to improve the results from your deep neural network using convolutions. It was a good start, but the data you used was very basic. What happens when your images are larger, or if the features aren’t always in the same place? Andrew and Laurence discuss this to prepare you for what you’ll learn this week: handling complex images!
---------------------------------------------------------------
На прошлой неделе вы увидели, как улучшить результаты вашей глубокой нейронной сети с помощью сверток. Это было хорошее начало, но данные, которые вы использовали, были очень простыми. Что происходит, когда ваши изображения больше или если функции не всегда находятся в одном и том же месте? Эндрю и Лоуренс обсуждают это, чтобы подготовить вас к тому, чему вы научитесь на этой неделе: работе со сложными изображениями!

(w4) Learning Objectives: (15.MLg_1c)

● Reflect on the possible shortcomings of your binary classification model implementation
● Execute image preprocessing with the Keras ImageDataGenerator functionality
● Carry out real life image classification by leveraging a multilayer neural network for binary classification
---------------------------------------------------------------
● Подумайте о возможных недостатках реализации вашей модели бинарной классификации.
● Выполнение предварительной обработки изображений с помощью функции Keras ImageDataGenerator.
● Выполняйте классификацию реальных изображений, используя многослойную нейронную сеть для бинарной классификации.

1(w4)-video1: A conversation with Andrew Ng (15.MLg_1c)

So, there we saw that the classifier that we built for classifying fashion, like using convolutions were able to make it more efficient and to make it more accurate. I thought that was really, really cool, but it's still very limited in the scenario because all of our images are 28 by 28 and the subject is actually centered. And while it's a fabulous dataset for learning, it's like when we start getting into real-world images and complex images that maybe we need to go a little bit further. What do you think? I think it's really cool that taking the core idea of a confinet allows you to implement an algorithm to confine not just handbags right in the middle of the image but anywhere in the image, so it could be carried by someone on the left or the right of a much bigger and, say, a one-megapixel image. This is 1000 by 1000 pixels. Also for many applications rather than using grayscale, want to use color images- All right. And the same core ideas but with a bigger dataset, bigger images in similar labels lets you do that. All right. So, the technique that you're learning in this, is really really helping you to be able to succeed in these more real-world scenarios. So, I know you've been working on a dataset on horses- Yeah. And humans. Yeah, that's been a lot of fun. I've been working on a dataset that's a number of images of horses and they're moving around the image and they're in different poses, and humans in the same way and diverse humans male, female, different races, that kind of thing to see if we can build a binary classifier between the two of them. But what was really interesting about this is that they're all computer-generated images, but we can use them to classify real photos. I had a lot of fun with that. So, I think there'll be a fun exercise for you to work on as well. And if you're ever wondering of these algorithms you're learning whether this is the real stuff, the algorithims you're learning is really the real stuff that is used today in many commercial applications. For example, if you look at the way a real self-driving car today uses cameras to detect other vehicles or pedestrians to try to avoid them, they use convolutional neural networks for that part of the task, very similar to what you are learning. And in fact, in other contexts, I've heard you speak about using a convolutional neural network. To take a picture, for example. Yeah, we can take a picture of a crop and try to tell if it has a disease coming. So, that was really cool. Oh, thank you, thank you. That's really fun. So, in the next video, you'll learn how to apply convolutional neural networks to these much bigger and more complex images. Please go on to the next video.
---------------------------------------------------------------
Мы увидели, что классификатор, который мы создали для классификации одежды с использованием свёрток, смог сделать классификацию эффективнее и точнее. Я думал, что это очень, очень круто, но всё ещё очень ограниченно в сценариях применения, т.к. все наши изображения имеют размерность 28х28, а объект расположен по центру. И хотя это потрясающий набор данных для изучения, но когда мы переходим к реальным изображениям, к сложным изображениям, то нам, возможно, нужно пойти чуть дальше. Что думаете? Я думаю — это действительно здорово, что основная идея свёрточной сети позволяет вам реализовать алгоритм, не ограниченный одними лишь сумочками, находящимися точно по центру изображения — а чтоб они были где угодно на картинке. Чтобы их можно было перемещать влево или вправо на гораздо большем изображении — скажем, в 1 мегапиксель. Это 1000х1000 пикселов. Также для многих приложений вместо полутоновых изображений хочется использовать цветные. Верно. И те же основные принципы, но с бо́льшим набором данных, бо́льшими по размеру изображениями и теми же метками — позволят вам это сделать. Всё верно. Тот метод, которому вы здесь учитесь, очень поможет вам суметь достичь успеха в реальных сценариях. Я знаю, что вы работаете над набором данных с лошадьми. >> Да. и людьми. Да, это очень увлекательно. Я работаю над набором данных. Это набор изображений лошадей, которые двигаются по изображению, они находятся в разных позах. И люди точно так же. Это разные люди: мужчины, женщины, разной расы, и так далее, — для того, чтобы посмотреть: сможем ли мы построить бинарный классификатор между людьми и лошадьми. Но что действительно было интересно — что все эти изображения были сгенерированы компьютером, но мы можем использовать их для классификации реальных фотографий. Я получил от этого массу удовольствия. Я думаю, что у нас также будет интересное упражнение и для вас. И если вы когда-нибудь задумывались, являются ли алгоритмы, которые вы изучаете, чем-то практичным, То я скажу: алгоритмы, которые вы изучаете — практичны, и используются сегодня во многих коммерческих приложениях. Например, если вы посмотрите на то, как реальные автопилоты на автомобилях используют камеры для обнаружения других транспортных средств или пешеходов, чтобы не столкнуться с ними, — то там для этой задачи применяются свёрточные нейронные сети, очень похожие на те, что вы изучаете. И на самом деле, в других областях, я слышал, как вы говорили об использовании свёрточной нейронной сети для того, чтобы, например, сделать снимок... Да, мы можем сделать снимок урожая и попытаться сказать, приближается ли болезнь. Это очень классно. О, спасибо, спасибо. Это действительно классно. В следующем видео вы научитесь применять свёрточные нейронные сети для куда более крупных и сложных изображений. Приглашаем вас перейти к следующему видео.

2(w4)-Explore an impactful, real-world solution: (15.MLg_1c)

(Узнайте об эффективном реальном решении)
As Andrew and Laurence discussed, the techniques you’ve learned already can apply to complex images, and you can start solving real scenarios with them. They discussed how it could be used, for example, in disease detection with the Cassava plant, and you can see a video demonstrating that here. Once you’ve watched that, move onto the next lesson!
https://www.youtube.com/watch?v=NlpS-DhayQA
---------------------------------------------------------------
Как обсуждали Эндрю и Лоуренс, методы, которые вы уже изучили, можно применять к сложным изображениям, и вы можете начать решать с их помощью реальные сценарии. Они обсудили, как его можно использовать, например, для обнаружения болезней с помощью растения маниоки, и вы можете посмотреть видео, демонстрирующее это здесь. После просмотра переходите к следующему уроку!

3(w4)-video2: Understanding ImageDataGenerator (15.MLg_1c)

To this point, you built an image classifier that worked using a deep neural network and you saw how to improve its performance by adding convolutions. One limitation though was that it used a dataset of very uniform images. Images of clothing that was staged and framed in 28 by 28. But what happens when you use larger images and where the feature might be in different locations? For example, how about these images of horses and humans? They have different sizes and different aspect ratios. The subject can be in different locations. In some cases, there may even be multiple subjects. In addition to that, the earlier examples with a fashion data used a built-in dataset. All of the data was handily split into training and test sets for you and labels were available. In many scenarios, that's not going to be the case and you'll have to do it for yourself. So in this lesson, we'll take a look at some of the APIs that are available to make that easier for you. In particular, the image generator in TensorFlow. One feature of the image generator is that you can point it at a directory and then the sub-directories of that will automatically generate labels for you. So for example, consider this directory structure. You have an images directory and in that, you have sub-directories for training and validation. When you put sub-directories in these for horses and humans and store the requisite images in there, the image generator can create a feeder for those images and auto label them for you. So for example, if I point an image generator at the training directory, the labels will be horses and humans and all of the images in each directory will be loaded and labeled accordingly. Similarly, if I point one at the validation directory, the same thing will happen. So let's take a look at this in code. The image generator class is available in Keras.preprocessing.image. You can then instantiate an image generator like this. I'm going to pass rescale to it to normalize the data. You can then call the flow from directory method on it to get it to load images from that directory and its sub-directories. It's a common mistake that people point the generator at the sub-directory. It will fail in that circumstance. You should always point it at the directory that contains sub-directories that contain your images. The names of the sub-directories will be the labels for your images that are contained within them. So make sure that the directory you're pointing to is the correct one. You put it in the second parameter like this. Now, images might come in all shapes and sizes and unfortunately for training a neural network, the input data all has to be the same size, so the images will need to be resized to make them consistent. The nice thing about this code is that the images are resized for you as they're loaded. So you don't need to preprocess thousands of images on your file system. But you could have done that if you wanted to. The advantage of doing it at runtime like this is that you can then experiment with different sizes without impacting your source data. While the horses and humans dataset is already in 300 by 300, when you use other datasets they may not always be uniformly sized. So this is really useful for you. The images will be loaded for training and validation in batches where it's more efficient than doing it one by one. Now, there's a whole science to calculating batch size that's beyond the scope of this course, but you can experiment with different sizes to see the impact on the performance by changing this parameter. Finally, there's the class mode. Now, this is a binary classifier i.e. it picks between two different things; horses and humans, so we specify that here. Other options in particular for more than two things will be explored later in the course. The validation generator should be exactly the same except of course it points at a different directory, the one containing the sub-directories containing the test images. When you go through the workbook shortly, you'll see how to download the images as a zip, and then sort them into training and test sub-directories, and then put horses and humans sub-directories in each. That's just pure Python. It's not TensorFlow or any other deep learning stuff. But it's all explained for you in the notebook.
---------------------------------------------------------------
До этого момента вы делали классификатор изображений, работавший на основе глубокой нейронной сети, и вы посмотрели, как улучшить его результаты, добавляя свёртки. Впрочем, одно ограничение было связано с тем, что применялся набор однородных изображений. Изображений одежды, которые были подготовлены и вписаны в рамки 28х28. Но что происходит, при использовании более крупных изображений, где признаки могут находиться в разных их частях? Например, как насчёт этих изображений лошадей и людей? У них разные размеры и разные пропорции. Объект может быть в разных местах. Иногда может даже присутствовать несколько объектов. В дополнение к этому, в более ранних примерах с одеждой использовался встроенный набор данных. Все данные были удобным образом разделены на обучающий и тестовый наборы, и были доступны метки. Во многих сценариях такого не будет, и вам придется делать это самостоятельно. На этом уроке мы посмотрим на некоторые из API, позволяющие упростить эту задачу. В частности, генератор изображений (ImageGenerator) в TensorFlow. Одной из функций генератора изображений является то, что вы можете указать ему директорию, и по структуре её поддиректорий за вас автоматически будут сгенерированы метки. Например, рассмотрим вот эту структуру. У нас есть директория Images (изображения), в которой есть поддиректории Training(обучение) и Validation(проверка). Когда вы в них создаёте поддиректории для лошадей и людей и сохраняете в них необходимые изображения, то генератор изображений может создать раздатчик для этих изображений и автоматически их вам разметить. Так, например, если я укажу генератору изображений директорию для обучения, то метками будут "лошади" и "люди", а все изображения из каждой поддиректории будут загружены и размечены соответственно. Аналогичным образом, если я укажу директорию Validation, то произойдёт то же самое. Давайте посмотрим на это в коде. Класс ImageGenerator находится в keras.preprocessing.image. И далее вот таким образом можно создать экземпляр ImageGenerator. Я передам параметр rescale, чтобы нормализовать данные. Затем мы вызываем метод flow_from_directory, чтобы он загрузил изображения из этой директории и её поддиректорий. Распространённой ошибкой является то, что люди указывают генератору поддиректорию. В этом случае произойдёт ошибка. Вы всегда должны указывать директорию, содержащую поддиректории, в которых лежат изображения. Имена поддиректорий станут метками для содержащихся в них изображений. Поэтому убедитесь, что вы указали правильную директорию. Вы передаёте её как входной параметр вот здесь. Изображения могут быть любой формы и размера, но к сожалению, для обучения нейронной сети все входные данные должны быть одного размера. Поэтому изображения нужно отмасштабировать, чтобы привести к единому размеру. И в этом коде хорошо то, что изображения масштабируются во время загрузки. Поэтому вам не прийдётся предобрабатывать тысячи изображений в вашей файловой системе. Но вы могли бы это сделать, при желании. Преимущество подхода, когда вы делаете это в процессе исполнения, как здесь, — является то, что вы можете экспериментировать с различными размерами без изменения исходных данных. Хотя набор данных с лошадьми и людьми сам по себе размером 300х300, но если вы будете использовать другие наборы, их содержимое не всегда будет одного размера. Поэтому это будет вам очень полезно. Изображения для обучения и проверки будут загружаться пакетами, когда это эффективнее, чем загружать их по одному. Это целая наука — как посчитать размер пакета, и это выходит за рамки этого курса, но вы можете экспериментировать с различными размерами, меняя этот параметр, чтобы посмотреть, как это повлияет на результативность. Последний параметр — это class_mode. Здесь мы используем двоичный классификатор, т.е., он выбирает между двумя различными вещами: лошадьми и людьми — поэтому мы его здесь и указали. Другие варианты, в частности, когда классов больше двух, — будут рассмотрены далее в этом курсе. Проверочный генератор (validation_generator) должен быть точно таким же, за исключением, конечно, того, что он указывает на другую директорию. На ту, которая содержит поддиректории, содержащие тестовые изображения. Если вы бегло пройдёте по рабочей тетради, то увидите, как скачать изображения в виде zip-архива, рассортировать их по поддиректориям для обучения и для тестов, а затем поместить поддиректории с лошадьми и людьми в каждую из них. Это всё чистый Python. Это не TensorFlow или что-то ещё, касающееся глубокого обучения. Но это всё поясняется в тетради.

4(w4)-Designing the neural network: (15.MLg_1c)

(Проектирование нейронной сети)
Now that you’ve seen how an ImageDataGenerator can flow images from a directory and perform operations such as resizing them on the fly, the next thing to do is design the neural network to handle these more complex images. You’ll see that in the next video.
---------------------------------------------------------------
Теперь, когда вы увидели, как ImageDataGenerator может передавать изображения из каталога и выполнять такие операции, как изменение их размера на лету, следующее, что нужно сделать, — это спроектировать нейронную сеть для обработки этих более сложных изображений. Вы увидите это в следующем видео.

5(w4)-video3: Defining a ConvNet to use complex images (15.MLg_1c)

(Определение ConvNet для использования сложных изображений)
So let's now take a look at the definition of the neural network that we'll use to classify horses versus humans. It's very similar to what you just used for the fashion items, but there are a few minor differences based on this data, and the fact that we're using generators. So here's the code. As you can see, it's the sequential as before with convolutions and pooling before we get to the dense layers at the bottom. But let's highlight some of the differences. First of all, you'll notice that there are three sets of convolution pooling layers at the top. This reflects the higher complexity and size of the images. Remember our earlier our 28 by 28.5 to 13 and then five before flattening, well, now we have 300 by 300. So we start at 298 by 298 and then have that etc., etc. until by the end, we're at a 35 by 35 image. We can even add another couple of layers to this if we wanted to get to the same ballpark size as previously, but we'll keep it at three for now. Another thing to pay attention to is the input shape. We resize their images to be 300 by 300 as they were loaded, but they're also color images. So there are three bytes per pixel. One byte for the red, one for green, and one for the blue channel, and that's a common 24-bit color pattern. If you're paying really close attention, you can see that the output layer has also changed. Remember before when you created the output layer, you had one neuron per class, but now there's only one neuron for two classes. That's because we're using a different activation function where sigmoid is great for binary classification, where one class will tend towards zero and the other class tending towards one. You could use two neurons here if you want, and the same softmax function as before, but for binary this is a bit more efficient. If you want you can experiment with the workbook and give it a try yourself. Now, if we take a look at our model summary, we can see the journey of the image data through the convolutions The 300 by 300 becomes 298 by 298 after the three by three filter, it gets pulled to 149 by 149 which in turn gets reduced to 73 by 73 after the filter that then gets pulled to 35 by 35, this will then get flattened, so 64 convolutions that are 35 squared and shape will get fed into the DNN. If you multiply 35 by 35 by 64, you get 78,400, and that's the shape of the data once it comes out of the convolutions. If we had just fed raw 300 by 300 images without the convolutions, that would be over 90,000 values. So we've already reduced it quite a bit.
---------------------------------------------------------------
Давайте сейчас посмотрим на определение нейронной сети, которую мы будем использовать для различения лошадей от людей. Она очень похожа на ту, что вы недавно использовали для предметов одежды, но есть несколько незначительных отличий, связанных с данными, и с тем, что мы используем генераторы. Вот он, код. Как вы можете видеть — это, как и раньше, последовательная модель со свёрточными слоями и пулингом, после которых уже мы добираемся до полносвязных слоёв внизу. Но давайте остановимся на некоторых различиях. Во-первых, можно видеть, что здесь сверху три набора слоёв "свёртка + пулинг". Это отражает более высокую сложность и размер изображений. Помните, ранее наши картинки 28х28 перед развертыванием сокращались сперва вдвое — до 13, а затем до 5. Сейчас же у нас изображения 300х300. Поэтому мы начинаем с 298х298, а затем сокращаем его вдвое снова и снова, пока в конце концов не дойдём до изображения 35х35. Можно было бы добавить и еще пару слоёв, если бы мы хотели достичь примерно того же размера, что и раньше, но пока оставим три. Еще одна вещь, на которую стоит обратить внимание, — это размерность входных данных. Мы масштабируем изображения к размеру 300х300 при их загрузке, но они, к тому же, являются цветными изображениями. Поэтому в них хранится по 3 байта на пиксел. Один байт для красного, один для зелёного, и один для синего канала, это типовая 24-битная цветовая палитра. И если как следует присмотреться, то вы увидите, что выходной слой также изменился. Вспомните, раньше при создании выходного слоя у вас был один нейрон на каждый класс, но теперь у нас только один нейрон для двух классов. Это потому, что мы сейчас используем другую функцию активации, и сигмоида отлично подходит для бинарной классификации. С ней один класс будет стремиться к 0, а другой класс будет стремиться к 1. Вы бы могли здесь, при желании, использовать 2 нейрона и ту же softmax функцию, что и прежде, но для двоичного случая нынешний вариант чуть эффективнее. Если вы хотите, то можете поэкспериментировать с рабочей тетрадью и проверить это самостоятельно. Если мы теперь посмотрим на сводку по нашей модели, то увидим весь путь, который проходит изображение через свёртки. Картинка 300х300 становится 298х298 после прохождения фильтра 3х3, далее оно сжимается до 149х149, что, в свою очередь, сокращается до 73х73 после фильтра, и затем происходит сжатие до 35х35. Затем это всё разворачивается, то есть, разворачиваются 64 свёртки 35х35, и результат идёт на вход полносвязной нейронной сети. Если вы перемножите 35 * 35 * 64, то получите 78,400, и это та размерность данных, которые получаются на выходе свёрток. Если бы мы просто скармливали оригинальные изображения 300х300 без свёрток, то это было бы более 900,000 значений. Так что мы уже ощутимо сократили их число.

6(w4)-Train the ConvNet with ImageDataGenerator: (15.MLg_1c)

(Train the ConvNet with ImageDataGenerator)
Now that you’ve designed the neural network to classify Horses or Humans, the next step is to train it from data that’s on the file system, which can be read by generators. You'll see how to do this in the next video.
---------------------------------------------------------------
Теперь, когда вы разработали нейронную сеть для классификации лошадей или людей, следующим шагом будет ее обучение на основе данных, находящихся в файловой системе, которые могут быть прочитаны генераторами. Как это сделать, вы увидите в следующем видео.

7(w4)-video4: Training the ConvNet (15.MLg_1c)

Okay, we'll now compile the model and, as always, we have a loss function and an optimizer. When classifying the ten items of fashion, you might remember that your loss function was a categorical cross entropy. But because we're doing a binary choice here, let's pick a binary_crossentropy instead. Also, earlier we used an Adam optimizer. Now, you could do that again, but I thought it would be fun to use the RMSprop, where you can adjust the learning rate to experiment with performance. To understand learning rate and how all that fits together, check out this great video from deeplearning.ai that goes into it in a lot more detail.
For now, I'm not going to go into the details in this course. Okay, next up is the training, now, this looks a little different than before when you called model.fit. And that's because we're using a generator instead of datasets. Remember the image generator from earlier, let's look at each parameter in detail. The first parameter is the training generator that you set up earlier. This streams the images from the training directory. Remember the batch size you used when you created it? That's important in the next step. There are 1,024 images in the training directory, so we're loading them in 128 at a time. So in order to load them all, we need to do 8 batches. So we set the steps_per_epoch to cover that.
Here we just set the number of epochs to train for. This is a bit more complex, so let's use, say, 15 epochs in this case. And now we specify the validation set that comes from the validation_generator that we also created earlier. It had 256 images, and we wanted to handle them in batches of 32, so we will do 8 steps.
And the verbose parameter specifies how much to display while training is going on. With verbose set to 2, we'll get a little less animation hiding the epoch progress. Once the model is trained, you will, of course, want to do some prediction on the model. And here's the code to do that, let's look at it piece by piece.
So these parts are specific to Colab, they are what gives you the button that you can press to pick one or more images to upload. The image paths then get loaded into this list called uploaded. The loop then iterates through all of the images in that collection. And you can load an image and prepare it to input into the model with this code. Take note to ensure that the dimensions match the input dimensions that you specified when designing the model. You can then call model.predict, passing it the details, and it will return an array of classes. In the case of binary classification, this will only contain one item with a value close to 0 for one class and close to 1 for the other.
Later in this course you'll see multi-class classification with Softmax. Where you'll get a list of values with one value for the probability of each class and all of the probabilities adding up to 1
---------------------------------------------------------------
Теперь скомпилируем модель, и как обычно, у нас есть функция потерь и оптимизатор. Как вы, наверное, помните, при классификации десяти предметов одежды функцией потерь — была categorical_crossentropy. Но т.к. здесь мы делаем бинарный выбор, то давайте возьмём binary_crossentropy. Также ранее мы использовали оптимизатор Adam. Сейчас вы могли бы сделать это снова, но я подумал, что было бы любопытно использовать RMSprop, где вы можете настроить скорость обучения, чтобы поэкспериментировать с качеством. Чтобы понять, что такое скорость обучения, и как всё это связано — посмотрите отличное видео от deeplearning.ai (https://youtu.be/zLRB4oupj6g), в котором это объясняется куда подробнее.
А пока я не буду вдаваться в такие детали в этом курсе. Хорошо, следующий шаг — это обучение. Оно выглядит немного иначе, чем раньше, когда вы вызывали model.fit(). Потому что теперь вы вызываете model.fit_generator(), поскольку мы используем генератор вместо наборов данных. Вспомните генератор изображений, который у нас был, и рассмотрим каждый параметр вызова подробнее. Первый параметр — это train_generator, который вы настраивали ранее. Он выдаёт поток изображений из директории для обучения. Помните, при его создании мы задавали размер пакетов, он был равен 128. [оговорка в оригинале - прим.] Это важно для следующего шага. В директории для обучения находится 1024 изображения, и мы загружаем их по 128 штук за раз. Поэтому для того, чтобы загрузить их все, нам нужно сделать 8 пакетов. Соответственно, мы установили steps_per_epoch=8, чтобы это обеспечить.
Здесь (epochs=15) мы просто указываем количество эпох для обучения. Эта тема несколько сложнее, поэтому давайте использовать здесь, скажем, 15 эпох. А сейчас мы указываем набор данных для валидации, который нам даст validation_generator, также созданный ранее. Он содержит 256 изображений, и мы хотели обрабатывать их пакетами по 32 штуки. Так что мы будем делать по 8 шагов.
А параметр verbose определяет, сколько информации отображать во время обучения. При verbose=2 мы получим немного меньше анимации, скрывая продвижение по эпохам. Как только модель обучена, вы, конечно же, захотите сделать несколько предсказаний с её помощью. И вот он код, чтобы это сделать. Давайте разберём его по частям.
Вот эти части специфичны для Colab, это даст нам кнопку, которую можно нажать для загрузки следующей порции изображений. Пути к изображениям будут загружены в этот список с названием uploaded. Далее следует цикл, проходящий по всем изображениям в этой коллекции. Данный код позволит вам загрузить изображение и подготовить его для передачи в модель. Проверьте, чтобы его размерность совпадала с размерностью входа, которую вы определили при проектировании модели. Затем можно вызвать model.predict, передавая в неё детали, — и она вернёт массив классов. В случае бинарной классификации, он будет содержать лишь один элемент со значением, близким к 0 для первого класса, и близким к 1 для второго.
Далее в этом курсе вы увидите мультиклассовую классификацию, использующую Softmax, где на выходе будет список значений, каждое из которых соответствует вероятности своего класса, и сумма всех вероятностей равна 1.

8(w4)-Exploring the solution: (15.MLg_1c)

(Изучение решения)
Now you’ve gone through the code to define the neural network, train it with on-disk images, and then predict values for new images. Let’s see this in action in a workbook. In the next video, Laurence will step you through the code, and afterward, you can try it for yourself.
---------------------------------------------------------------
Теперь вы прошли через код, чтобы определить нейронную сеть, обучить ее изображениям на диске, а затем предсказать значения для новых изображений. Давайте посмотрим на это в действии в рабочей тетради. В следующем видео Лоуренс покажет вам код, после чего вы сможете попробовать его сами.

9(w4)-video5: Walking through developing a ConvNet (15.MLg_1c)

(Прохождение разработки ConvNet)
Okay. So you've just seen how to get started with creating a neural network in Keras that uses the image generator to automatically load and label your files based on their subdirectories. Now, let's see how we can use that to build a horses or humans classifier with a convolutional neural network. This is the first notebook you can try. To start, you'll download the zip file containing the horses and humans data. Once that's done, you can unzip it to the temp directory on this virtual machine. The zip file contain two folders; one called filtered horses, and one called filtered humans. When it was unzipped, these were created for you. So we'll just point a couple of variables at them, and then we can explore the files by printing out some of the filenames. Now, these could be used to generate labels, but we won't need that if we use the Keras generator. If you wanted to use this data without one, a filenames will have the labels in them of course though. We'll print out the number of images that we have to work with, and there's a little over 1000 of them, and now we can display a few random images from the dataset. Here, we can see eight horses and eight humans. An interesting aspect of this dataset is that all of the images are computer-generated. I've rendered them to be as photo-real as possible, but there'll be actually used to classify real pictures of horses and people, and here's a few more images just to show some of the diversity. Let's start building the model. First, we'll import TensorFlow, and now we'll build the layers. We have quite a few convolutions here because our source images are quite large, are 300 by 300. Later we can explore the impact of reducing their size and needing less convolutions. We can print the summary of the layers, and here we can see by the time we reach the dense network, the convolutions are down to seven-by-seven. Okay. Next up, we'll compile our network. It's using binary cross entropy as the loss, binary because we're using just two classes, and the optimizer is an RMSprop that allows us to tweak the learning rate. Don't worry if you don't fully understand these yet, there are links out to content about them where you can learn more.
---------------------------------------------------------------
Вы только что увидели, как начать создавать в Keras нейронную сеть, использующую генератор изображений для автоматической загрузки и разметки ваших файлов на основе поддиректорий, где они лежат. А сейчас давайте посмотрим, как можно это использовать при построении классификатора лошадей и людей с помощью свёрточной нейронной сети. Это первый блокнот для ваших экспериментов. Чтобы начать, вы должны загрузить zip-файл, содержащий данные с лошадьми и людьми. Как только это будет сделано, вы можете распаковать его во временный каталог на этой виртуальной машине. Zip-файл содержит две папки: одна называется filtered_horses, а другая называется filtered_humans. Они будут созданы в результате распаковки архива. Поэтому мы просто создадим пару переменных, ссылающихся на них, и тогда можно изучить их содержимое, выведя имена некоторых файлов на экран. Можно использовать их для создания меток, но нам это не нужно, если мы используем генератор Keras. Если вы хотите использовать эти данные без него, то имена файлов, разумеется, будут содержать в своём составе метки. Мы выведем количество изображений, с которыми прийдётся работать. Их немногим более 1000, и теперь мы можем отобразить несколько случайно выбранных изображений из набора данных. Вы видите здесь восемь лошадей и восемь людей. Любопытная черта этого набора данных — в том, что все изображения были сгенерированы компьютером. Я отрендерил их так, чтобы они были максимально фотореалистичны, поскольку на самом деле они будут использованы для классификации реальных фотографий лошадей и людей. И вот ещё несколько изображений, чтобы просто показать их разнообразие. Давайте начнём строить модель. Сначала импортируем TensorFlow, а здесь построим слои. У нас здесь немало свёрток, поскольку исходные изображения достаточно большие, размером 300х300. Позже мы рассмотрим, как повлияет уменьшение их размера и потребность в меньшем числе свёрток. Мы можем вывести сводную информацию о слоях, и здесь видно, что к моменту достижения полносвязной сети свёртки уменьшатся до размера 7х7. Следующим шагом мы скомпилируем сеть. Здесь используется binary_crossentropy в качестве функции потерь. Бинарная, т.к. мы используем только 2 класса. А в качестве оптимизатора выбран RMSprop, который позволяет нам настроить темп обучения. Не волнуйтесь, если вы пока не до конца всё это понимаете. Перейдя по указанным ссылкам, вы можете узнать об этом больше.

10(w4)-Training the neural network: (15.MLg_1c)

Now that you’ve learned how to download and process the horses and humans dataset, you’re ready to train. When you defined the model, you saw that you were using a new loss function called ‘Binary Crossentropy’,
https://gombru.github.io/2018/05/23/cross_entropy_loss/
, and a new optimizer
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
called RMSProp.
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/experimental/RMSprop
f you want to learn more about the type of binary classification we are doing here, check out this
https://www.youtube.com/watch?v=eqEc66RFY0I&t=6s
great video from Andrew!
---------------------------------------------------------------
Теперь, когда вы научились загружать и обрабатывать набор данных о лошадях и людях, вы готовы к обучению. Когда вы определили модель, вы увидели, что используете новую функцию потерь под названием «Бинарная кроссэнтропия».
https://gombru.github.io/2018/05/23/cross_entropy_loss/
, и новый оптимизатор
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
называется RMSProp.
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/experimental/RMSprop
Если вы хотите узнать больше о типе бинарной классификации, которую мы здесь делаем, ознакомьтесь с этим
https://www.youtube.com/watch?v=eqEc66RFY0I&t=6s
отличное видео от Андрея!

11(w4)-video6: Walking through training the ConvNet (15.MLg_1c)

Next up is where we use the ImageDataGenerator. We instantiate it and we scale our images to 1 over 255, which then normalizes their values. We then point it at the main directory where we see the unzipped files.
We can see that it finds all of the images, and has assigned them to two classes, because they were two sub directories.
We'll now train the neural network for 15 epochs, it will take about two minutes.
Each epoch is loading the data, calculating the convolutions and then trying to match the convolutions to labels. As you can see, the accuracy mostly increases but it will occasionally dip, showing the gradient ascent of the learning actually in action.
It's always a good idea to keep an eye on fluctuations in this figure. And if there are too wild, you can adjust the learning rate.
Remember the parameter to RMS prop when you compile the model, that's where you'd tweak it. It's also going pretty fast, because right here, I'm training on a GPU machine.
By the time we get to epoch 15, we can see that our accuracy is about 0.9981, which is really good. But remember, that's only based on the data that the network has already seen during training, which is only about 1,000 images. So don't get lulled into a false sense of security.
Let's have a bit of fun with the model now and see if we can predict the class for new images that it hasn't previously seen.
Let's go to Pixelbay, and see what we can find. I'll search for horses, and there's lots of horses, so let's pick this one. It's a white horse running in the snow. I'm going to download it to my file system. I'm now going to go back to the notebook, and I'm going to upload the image from my file system. And we'll see that it gets uploaded, and it's classified as a horse. So let's try another one. Like this one here. Which I'll then upload to the notebook, and we'll see that it's also classified as a horse.
I'll now go back to Pixelbay and search for person, and pick this image of a girl sitting on a bench. I'll download it to my file system, upload it to the neural network, and we can see that this is also correctly classified as a human.
Let's do one more. I'll go back to the list of results on Pixelbay, and pick this image of a girl. As before, I'll download it to my file system and I'll upload it to the neural network and we'll also see that it's still detects a human in the image.
Now one other thing that I can do with this script is upload multiple files and have it classify all of them at once. And here we can see all of the classifications. We have four out four correct.
This notebook also includes some visualizations of the image as it passes through the convolutions. You can give it a try with this script.
Here you can see where a human image was convolved and features such as the legs really lit up. And if I run it again, we can see another human with similar features. Also the hair is very distinctive. Have a play with it for yourself and see what you discover.
So there, we saw a convolutional neural network create a classifier to horses or humans using a set of about 1,000 images. The four images we tested all worked, but that's not really scalable. And the next video, we'll see how we can add a validation set to the training and have it automatically measure the accuracy of the validation set, too.
---------------------------------------------------------------
Следующим шагом будет использование ImageDataGenerator. Мы создаём экземпляр этого класса и умножаем значения пикселов на 1/255, что нормализует их значения. Затем мы задаём ему основную директорию, где находятся распакованные файлы.
Мы видим, что генератор нашёл все изображения, и отнёс их двум классам, ведь они находились в двух поддиректориях. А сейчас мы обучим нейронную сеть за 15 эпох, что займёт около двух минут.
В каждой эпохе загружаются данные, просчитываются свёртки, а затем выполняется попытка сопоставить свёртки их меткам. Как вы видите, точность в большинстве случаев увеличивается, но иногда и проседает вниз, отражая работу градиентного спуска при обучении.
Будет полезно всегда следить за его колебаниями, и если они слишком резкие, то можно отрегулировать темп обучения.
Помните параметр RMSprop, заданный при компиляции модели? Вот где вы можете подстроить темп. Обучение проходит довольно быстро, поскольку сейчас я обучаю сеть на машине с GPU.
Между тем, мы дошли до 15 эпохи, и видим, что наша точность в районе 0.9981, что очень здорово. Но помните, что это лишь на тех данных, которые сеть уже видела во время обучения, где всего около 1,000 изображений. Поэтому не полагайтесь на ложное чувство уверенности.
Давайте теперь немного поиграемся с моделью, и посмотрим, сможем ли мы предугадать класс для новых изображений, которые сеть не видела ранее.
Давайте зайдём на Pixabay и посмотрим, что там можно найти. Я поищу лошадей, и здесь куча лошадей. Давайте возьмём вот эту. Это белая лошадь, бегущая по снегу. Я скачаю её к себе на диск. Теперь возвращаемся назад к блокноту, и загрузим изображение с моей файловой системы. И мы видим, что оно загрузилось, и было классифицировано как лошадь. Давайте попробуем другое изображение. Вот это, например. Которое я загружаю в блокнот, и мы видим, что оно также было классифицировано как лошадь.
Теперь я возвращаюсь на Pixabay и поищу человека. Возьмём это изображение девочки, сидящей на скамье. Загружаем его в файловую систему, далее загрузим его в нейронную сеть, и мы увидим, что оно было также корректно классифицировано как человек.
Давайте возьмём ещё одно. Я возвращаюсь к результатам поиска на Pixabay и возьму вот это изображение девочки. Как и раньше, я скачаю его, а затем загружу его в нейронную сеть — и мы снова видим, что сеть по-прежнему находит человека на изображении.
Ещё я в этом скрипте могу сделать вот что: загрузить разом несколько файлов и классифицировать их все. Здесь мы видим все результаты классификации. Четыре из четырёх классифицированы верно.
Этот блокнот также содержит некоторую визуализацию того, как изображение проходит через свёртки. Вы можете попробовать её с помощью этого скрипта.
Мы здесь можем увидеть, как изображение человека было свёрнуто, и такие признаки, как ноги, действительно проявились. И если я выполню его снова, то мы увидим другого человека с похожими признаками. Волосы также являются сильной отличительной чертой. Поиграйтесь с этим самостоятельно и посмотрите, что вы обнаружите.
Итак, здесь мы увидели как с помощью свёрточной нейронной сети создать классификатор лошадей и людей, используя набор из порядка 1,000 изображений. Все 4 изображения, на которых мы его протестировали — работали, но всё это не очень масштабируемо. И в следующем видео мы увидим, как можно добавить проверочный набор к обучению, чтобы автоматически измерять точность также и на проверочном наборе данных.

12(w4)-Experiment with the horse or human classifier (Lab 1): (15.MLg_1c)

Now it’s your turn. You can find the notebook here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W4/ungraded_labs/C1_W4_Lab_1_image_generator_no_validation.ipynb
Work through it and get a feel for how the ImageGenerator is pulling the images from the file system and feeding them into the neural network for training. Have some fun with the visualization code at the bottom!
In earlier notebooks, you tweaked parameters like epochs, or the number of hidden layers and neurons in them. Give that a try for yourself, and see what the impact is. Spend some time on this.
Once you’re done, move to the next video, where you can validate your training against a lot of images!
---------------------------------------------------------------
Теперь твоя очередь. Блокнот можно найти здесь.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W4/ungraded_labs/C1_W4_Lab_1_image_generator_no_validation.ipynb
Поработайте над этим и почувствуйте, как ImageGenerator извлекает изображения из файловой системы и передает их в нейронную сеть для обучения. Повеселитесь с кодом визуализации внизу!
В более ранних записных книжках вы настраивали такие параметры, как эпохи или количество скрытых слоев и нейронов в них. Попробуйте сами и посмотрите, каков будет эффект. Потратьте на это некоторое время.
Как только вы закончите, переходите к следующему видео, где вы можете проверить свою тренировку на множестве изображений!

13(w4)-video7: Adding automatic validation to test accuracy (15.MLg_1c)

(Добавление автоматической проверки точности теста)
In the previous video, you saw how to build a convolutional neural network that classified horses against humans. When you are done, you then did a few tests using images that you downloaded from the web. In this video, you'll see how you can build validation into the training loop by specifying a set of validation images, and then have TensorFlow do the heavy lifting of measuring its effectiveness with that same. As before we download the dataset, but now will also download the separate validation dataset. We'll unzip into two separate folders, one for training, one for validation. We'll create some variables that pointed our training and validation subdirectories, and we can check out the filenames. Remember that the filenames may not always be reliable for labels. For example, here the validation horse labels aren't named as such while the human ones are. We can also do a quick check on whether we got all the data, and it looks good so we think we can proceed. We can display some of the training images as we did before, and let's just go straight to our model. Here we can import TensorFlow, and here we define the layers in our model. It's exactly the same as last time. We'll then print the summary of our model, and you can see that it hasn't changed either. Then we'll compile the model with the same parameters as before. Now, here's where we can make some changes. As well as an image generator for the training data, we now create a second one for the validation data. It's pretty much the same flow. We create a validation generator as an instance of image generator, re-scale it to normalize, and then pointed at the validation directory. When we run it, we see that it picks up the images and the classes from that directory. So now let's train the network. Note the extra parameters to let it know about the validation data. Now, at the end of every epoch as well as reporting the loss and accuracy on the training, it also checks the validation set to give us loss in accuracy there. As the epochs progress, you should see them steadily increasing with the validation accuracy being slightly less than the training. It should just take about another two minutes. Okay. Now that we've reached epoch 15, we can see that our accuracy is about 97 percent on the training data, and about 85 percent on the validation set, and this is as expected. The validation set is data that the neural network hasn't previously seen, so you would expect it to perform a little worse on it. But let's try some more images starting with this white horse.
We can see that it was misclassified as a human. Okay, let's try this really cute one.
We can see that's correctly classified as a horse. Okay, let's try some people.
Let's try this woman in a blue dress. This is really interesting picture because she has her back turned, and her legs are obscured by the dress, but she's correctly classified as a human. Okay, here's a tricky one. To our eyes she's human, but will the wings confuse the neural network?
And they do, she is mistaken for a horse. It's understandable though particularly as the training set has a lot of white horses against the grassy background.
How about this one? It has both a horse and the human in it, but it gets classified as a horse. We can see the dominant features in the image are the horse, so it's not really surprising. Also there are many white horses in the training set, so it might be matching on them. Okay one last one. I couldn't resist this image as it's so adorable, and thankfully it's classified as a horse. So, now we saw the training with a validation set, and we could get a good estimate for the accuracy of the classifier by looking at the results with a validation set. Using these results and understanding where and why some inferences fail, can help you understand how to modify your training data to prevent errors like that. But let's switch gears in the next video. We'll take a look at the impact of compacting your data to make training quicker.
---------------------------------------------------------------
В предыдущем видео вы увидели, как построить свёрточную нейронную сеть, которая отличала лошадей от людей. После того, как вы это сделали, вы выполнили несколько тестов, используя изображения, которые скачали из интернета. В этом видео вы увидите, как можно встроить проверку в цикл обучения, указав набор проверочных изображений. И тогда TensorFlow сделает всю грязную работу по измерению эффективности с этим набором. Как и раньше, мы скачаем набор данных. Но на этот раз мы также скачаем отдельно и проверочный набор. Мы распакуем их в две отдельные папки: одну для обучения и одну для проверки. Мы создадим несколько переменных, указывающих на наши поддиректории для обучения и для проверки, и мы можем проверить названия файлов. Помните, что названия файлов не всегда могут надёжно отражать метки. Например, здесь метки лошадей в проверочном наборе не соответствуют названиям, хотя для меток людей это так. Мы также можем выполнить быструю проверку того, все ли данные мы получили. Вроде бы всё хорошо, поэтому, думаю, мы можем продолжать. Мы можем отобразить некоторые из учебных изображений, как мы это делали раньше. И давайте перейдём прямо к нашей модели. Здесь мы можем импортировать TensorFlow, а здесь мы определяем слои нашей модели. Всё точно так же, как в прошлый раз. Затем мы выведем информацию по нашей модели, и вы видите, что она вообще не изменилась. Далее скомпилируем модель с теми же параметрами, как и раньше. А вот здесь мы можем сделать кое-какие изменения. В дополнение к генератору изображений для обучающих данных, мы создадим второй такой же, но для проверочных данных. Это по сути все те же действия. Мы создаём validation_generator как экземпляр ImageGenerator, изменяем масштаб значений для нормализации и указываем ему путь к проверочной директории. Когда мы запустим его, то увидим, что он подхватил изображения и классы из этой директории. А теперь давайте обучим сеть. Обратите внимание на дополнительные параметры, указывающие модели на проверочные данные. Теперь в конце каждой эпохи, помимо вывода потерь и точности обучения, производится проверка на проверочных данных, чтобы выдать нам соответствующие потери и точность. По мере прохождения эпох вы должны видеть, что они постоянно растут, а точность на проверочных данных немного меньше, чем на обучающих. Это должно занять ещё две минуты. Готово. Теперь, когда мы достигли 15 эпохи, мы видим, что наша точность около 97% на обучающих данных и около 85% на проверочных данных. И это то, что и ожидалось. Проверочный набор — это данные, которые нейронная сеть раньше не видела, поэтому было ожидаемо, что она будет работать с ними немного хуже. Но давайте попробуем ещё несколько изображений. Начнём с этой белой лошади.
И мы видим, что она была ошибочно классифицирована как человек. Хорошо, давайте попробуем вот эту симпатичную лошадь.
Мы видим, что она была правильно классифицирована как лошадь. Так, а теперь давайте попробуем несколько людей.
Давайте попробуем вот эту женщину в синем платье. Это действительно интересная картинка, т.к. она повёрнута спиной, а её ноги скрыты за платьем, но она всё же правильно классифицирована как человек. А теперь картинка посложнее. Мы видим здесь человека, но собьют ли с толку 'крылья' нейронную сеть?
Да, сбили — она ошибочно решила, что здесь лошадь. Это можно понять, особенно когда обучающий набор содержит кучу белых лошадей на фоне травы.
Как насчёт вот этого изображения? На нём есть оба: и лошадь и человек,
Но оно было классифицировано как лошадь. Мы видим, что преобладающие признаки на изображении относятся к лошади, поэтому это не так уж и неожиданно. Также в обучающем наборе много белых лошадей, и, возможно, изображение похоже на них. Так, последнее. Я не смог пропустить это изображение, так как оно очаровательно, и, к счастью, оно было классифицировано как лошадь. Мы только что увидели обучение с проверочным набором, и мы смогли получить хорошую оценку для точности классификатора, глядя на результаты на проверочном наборе. Использование этих результатов и понимание, где и почему некоторые выводы были ложными, может помочь вам понять, как изменить ваши обучающие данные, чтобы предотвратить подобные ошибки. Но давайте в следующем видео перейдём на следующую скорость. Мы посмотрим как сжатие данных влияет на возможность ускорить обучение.

14(w4)-Get hands-on and use validation (Lab 2): (15.MLg_1c)

(Получите практический опыт и используйте проверку (лабораторная работа 2))
Now you can give it a try for yourself. Here is the notebook that Laurence went through in the video. Have a play with it to see how it trains, and test some images yourself! Once you’re done, move on to the next video where you’ll compact your data to see the impact on training.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W4/ungraded_labs/C1_W4_Lab_2_image_generator_with_validation.ipynb
---------------------------------------------------------------
Теперь вы можете попробовать сами. Вот блокнот, который Лоуренс просматривал в видео. Поиграйте с ним, чтобы увидеть, как он тренируется, и протестируйте некоторые изображения сами! Как только вы закончите, перейдите к следующему видео, где вы будете сжимать свои данные, чтобы увидеть влияние на обучение.

15(w4)-video8: Exploring the impact of compressing images (15.MLg_1c)

(Изучение влияния сжатия изображений)
The images in the horses are humans dataset are all 300 by 300 pixels. So we had quite a few convolutional layers to reduce the images down to condensed features. Now, this of course can slow down the training. So let's take a look at what would happen if we change it to a 150 by a 150 for the images to have a quarter of the overall data and to see what the impact would be. We'll start as before by downloading and unzipping the training and test sets.
Then we'll point some variables in the training and test sets before setting up the model. First, we'll import TensorFlow and now we'll define the layers for the model. Note that we've changed the input shape to be 150 by 150, and we've removed the fourth and fifth convolutional max pool combinations. Our model summary now shows the layer starting with the 148 by 148, that was the result of convolving the 150 by 150. We'll see that at the end, we end up with a 17 by 17 by the time we're through all of the convolutions and pooling. We'll compile our model as before, and we'll create our generators as before, but note that the target size has now changed to 150 by 150.
Now we can begin the training, and we can see that after the first epoch that the training is fast, and accuracy and validation aren't too bad either. The training continues and both accuracy values will tick up.
Often, you'll see accuracy values that are really high like 1.000, which is likely a sign that you're overfitting. We reach the end, I have really high accuracy on the test data, about 0.99, which is much too high. The validation set is about 0.84, which is pretty good, but let's put it to the test with some real images.
Let's start with this image of the girl and the horse. It still classifies as a horse. Next, let's take a look at this cool horsey,and who's still correctly categorized.
These cuties are also correctly categorized, but this one is still wrongly categorized. But the most interesting I think is this woman. When we use 300 by 300 before and more convolutions, she was correctly classified. But now, she isn't. This is a great example of the importance of measuring your training data against a large validation set, inspecting where it got it wrong and seeing what you can do to fix it. Using this smaller set is much cheaper to train, but then errors like this woman with her back turned and her legs obscured by the dress will happen, because we don't have that data in the training set. That's a nice hint about how to edit your dataset for the best effect in training.
---------------------------------------------------------------
Все изображения в наборе данных с лошадьми и людьми имеют размер 300х300 пикселов. Поэтому у нас было немало свёрточных слоёв для уменьшения изображений до уплотнённых признаков. Разумеется, это может замедлить обучение. Давайте посмотрим, что произойдёт, если мы изменим размер изображений на 150х150, оставив четверть от всех данных, — увидим, каким будет эффект. Начнем, как и раньше, с загрузки и распаковки обучающего и тестового наборов.
Затем перед созданием модели определим несколько переменных, ссылающихся на обучающий и тестовый наборы. Сначала импортируем TensorFlow, а затем определим слои в модели. Обратите внимание, что мы изменили размерность входных данных на 150х150, и удалили четвёртую и пятую комбинации свёрточного и MaxPooling слоёв. Информация по нашей модели теперь показывает слои, начиная со 148х148, что является результатом свёртки 150х150. И мы видим, что в конце мы приходим к 17х17, когда пройдём все свёртки и сжатие. Скомпилируем нашу модель, как и раньше. И мы создаём наши генераторы так же, как и ранее, но обратите внимание, что целевой размер теперь изменён до 150х150.
Сейчас мы можем начать обучение, и мы видим, что после первой эпохи обучение становится быстрым, при этом точность и валидация тоже не так уж и плохи. Обучение продолжается, и оба значения точности растут.
Зачастую вы будете видеть действительно высокие значения точности — в районе 1.000, что, скорее всего, является симптомом переобучения. Мы достигли конца с очень высокой точностью на тренировочных данных, около 0.99, что слишком много. На проверочном наборе точность в районе 0.84, что довольно хорошо, но давайте теперь протестируем на нескольких реальных изображениях.
Давайте начнём с этого изображения девушки и лошади. Оно всё ещё распознаётся как лошадь. Далее, давайте посмотрим на вот эту классную лошадку.
И она всё ещё правильно распознаётся как лошадь.
Эти красотки также были правильно распознаны.
Но вот эта всё ещё распознаётся неправильно. Но самое интересное, я думаю, вот эта женщина. Когда мы ранее использовали изображения 300х300 и больше свёрток, то она распознавалась правильно. Но сейчас нет. Это хороший пример важности проверки результатов обучения на большом проверочном наборе, с изучением мест, где результат ошибочный, и поиском способов исправить эту ситуацию. Использование такого уменьшенного в размере набора — дешевле в обучении, но тогда будут случаться ошибки, как с этой отвернувшейся женщиной и её скрытыми за платьем ногами, — потому что у нас нет этих данных в обучающем наборе. Это хорошая подсказка о том, как можно менять ваш набор данных, чтобы получить наилучший эффект при обучении.

16(w4)-Get Hands-on with compacted images (Lab 3): (15.MLg_1c)

(Практический опыт работы со сжатыми изображениями (лабораторная работа 3))
Try this version version of the notebook where Laurence compacted the images. You can see that training times will improve, but that some classifications might be wrong! Experiment with different sizes -- you don’t have to use 150x150 for example!
---------------------------------------------------------------
Попробуйте эту версию блокнота, где Лоуренс уплотнил изображения. Вы можете видеть, что время обучения улучшится, но некоторые классификации могут быть неправильными! Поэкспериментируйте с разными размерами — например, вам не обязательно использовать 150 x 150!

17(w4)- Week 4 Quiz: (15.MLg_1c)

1) Using Image Generator, how do you label images?:
1. You have to manually do it (-)
2. TensorFlow figures it out from the contents
3. It's based on the file name
4. It's based on the directory the image is contained in(+)
2) What method on the Image Generator is used to normalize the image?:
1. rescale(+)
2. Rescale_image
3. Normalize_image (-)
4. Normalize
3 )How did we specify the training size for the images?:
1. The training_size parameter on the training generator
2. The target_size parameter on the training generator(+)
3. The training_size parameter on the validation generator
4. The target_size parameter on the validation generator
4) When we specify the input_shape to be (300, 300, 3), what does that mean?:
1. There will be 300 horses and 300 humans, loaded in batches of 3
2. There will be 300 images, each size 300, loaded in batches of 3
3. Every Image will be 300x300 pixels, and there should be 3 Convolutional Layers
4. Every image will be 300x300 pixels, with 3 bytes to define color (+)
5) If your training data is close to 1.000 accuracy, but your validation data isn't, what's the risk here?:
1. You're overfitting on your validation data
2. No risk, that's a great result
3. You're overfitting on your training data (+)
4. You're everfittting on your validation data
6) Convolution Neural Networks are better for classifying images like horses and humans because:
1. There's a wide variety of horses (- +)
2. There's a wide variety of humans (- +)
3. In these images, the features may be in different parts of the frame (+)
7) After reducing the size of the images, the training results were different. Why?:
1. There was more condensed information in the images
2. There was less information in the images (-)
3. The training was faster
4. We removed some convolutions to handle the smaller images (+)

18(w4)- Lecture Notes Week 4: (15.MLg_1c)

(Конспект лекций, неделя 4)
The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.DeepLearning.AI
https://www.deeplearning.ai
makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons License.DeepLearning.AI
https://www.deeplearning.ai
делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

19(w4)-Weekly Assignment: (15.MLg_1c)

Handling Complex Images (Обработка сложных изображений)
Now it is time to create your own image classifier for complex images. See if you can create a classifier for a set of happy or sad images.
To submit your Jupyter Notebook for grading, please click the Submit Assignment button while in the notebook.
IMPORTANT FOR SUCCESSFUL GRADING:
- Don't forget to save your notebook before submitting!
- Don't delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
Теперь пришло время создать собственный классификатор изображений для сложных изображений. Посмотрите, сможете ли вы создать классификатор для набора счастливых или грустных изображений.
Чтобы отправить блокнот Jupyter на оценку, нажмите кнопку «Отправить задание» в блокноте.
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не забудьте сохранить блокнот перед отправкой!
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

20(w4)-Wrap up: (15.MLg_1c)

Congratulations! You've reached the end of Course 1! You've come a long way from looking at the most basic of neural networks to building a basic computer vision neural network that classified clothing. You took this a little further by using convolutions that spot features in an image, and then classify and learn based on those features. In Course 2, you'll go a little deeper into convolutions by training networks with real-world images. You will also get to see many of the techniques used in challenges such as those run by Kaggle!
---------------------------------------------------------------
Поздравляем! Вы дошли до конца курса 1! Вы прошли долгий путь от изучения самых простых нейронных сетей до создания базовой нейронной сети компьютерного зрения, которая классифицировала одежду. Вы пошли немного дальше, используя свертки, которые обнаруживают функции на изображении, а затем классифицируют и изучают на основе этих функций. На курсе 2 вы немного углубитесь в свертки, обучая сети с изображениями реального мира. Вы также сможете увидеть многие методы, используемые в таких задачах, как те, которые проводит Kaggle!

21(w4)-video9: A conversation with Andrew (15.MLg_1c)

Congratulations on coming to the end of this first course, and well, you've come a long way. Yeah, I mean, we've looked at with the students like you looked at how to use TensorFlow, all the way from the beginning with doing something like fitting a straight line, to then like recognizing fashion items. It's really cool. It's like three lines of code to do a really complicated task like that. Isn't it amazing, computer vision in three lines like that? Then, we improve that by adding convolutions. We call it an improvement, but that means now four lines of code to define two conv layers and two maxpool layers, and then a two like TensorFlow take cares of a lot of the rest. Then, we looked at going beyond the simple images to bigger and colored images, and we didn't even add any lines of code for that, right? It was just changing the shape of the data coming in. Yeah. So by learning a framework like this, you can write very complicated programs with just a few lines of code, and this helps people save a lot of time. But there's still a lot more to learn. Oh there is, like some of the things that we'd love to explore are things such as, when you have very small data sets that can lead to an error called over-fitting. So we'll explore some techniques and tools that we can use to avoid that. Transfer learning. If you can download someone else's say TensorFlow model, and use that for your own problem, even though I was trained on a totally different data set, TensorFlow has tools that let you do that efficiently as well. Absolutely, and one of the things that a lot of AI practitioners love to be involved in is like this online competitions, where places like Kango provide a data set, and they ask you to build a classifier around that data set. We're going to explore some of the skills that you can use to take part in those competitions. So congratulations again on coming to the end of the first course and there's still all these amazing things to learn about TensorFlow. So please go on to the next course.
---------------------------------------------------------------
Поздравляю с тем, что вы дошли до конца этого первого курса, и да, вы прошли длинный путь. Да, мы увидели вместе со студентами, как использовать TensorFlow, на всём протяжении, от начала, когда делали что-то вроде нахождения прямой линии, — до таких вещей, как распознавание предметов одежды. Это очень круто. Всего три строчки кода, чтобы выполнить действительно сложную задачу вроде этой. Разве это не удивительно, компьютерное зрение в три строчки кода? Далее мы улучшили это, добавив свёртки. Мы называем это улучшением, но теперь это означает 4 строчки кода, чтобы определить 2 свёрточных слоя и 2 MaxPool слоя, и затем такой инструмент, как TensorFlow, позаботится обо всём остальном. Затем мы перешли от простых изображений к более крупным и цветным изображениям, и для этого даже не добавили ни одной строчки кода, верно? Мы просто изменили размерность входных данных. Так что изучив фреймворк, подобный этому, вы можете писать очень сложные программы, написав всего несколько строчек кода, и это помогает людям сэкономить кучу времени. Но ещё очень многое только предстоит изучить. Да, среди таких тем, которые мы хотели изучить, есть, например, то, что когда у вас очень маленькие наборы данных, то это может приводить к ошибке, называемой "переобучение". Поэтому мы будем изучать некоторые техники и инструменты, использование которых позволит нам этого избежать. И передача обучения. Если вы можете скачать скажем, чью-то модель TensorFlow, и использовать её для решения вашей задачи, даже если она была обучена на абсолютно другом наборе данных, то у TensorFlow также есть инструменты, которые позволят вам эффективно это сделать. Именно. И ещё одна вещь, в которой многие работающие с ИИ обожают принимать участие: это соревнования онлайн, где есть ресурсы вроде Kaggle, предоставляющие наборы данных, и они дают задание построить классификатор на основании этих данных. Мы собираемся рассмотреть некоторые из навыков, которые пригодятся для участия в этих соревнованиях. Итак, ещё раз поздравляю вас с тем, что дошли до конца первого курса, и впереди ещё множество потрясающих вещей в TensorFlow, которые предстоит изучить. Так что приглашаем вас перейти к следующему курсу.


16.MLg_2c


(w1) Exploring a Larger Dataset (16.MLg_2c)

(Изучение большего набора данных)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 17 minutes
Self-study: 52 minutes
Graded tasks (Tasks to be assessed): 2

(w1) Introduction: (16.MLg_2c)

In the first course in this specialization, you had an introduction to TensorFlow, and how, with its high level APIs you could do basic image classification, and you learned a little bit about Convolutional Neural Networks (ConvNets). In this course you'll go deeper into using ConvNets will real-world data, and learn about techniques that you can use to improve your ConvNet performance, particularly when doing image classification!In Week 1, this week, you'll get started by looking at a much larger dataset than you've been using thus far: The Cats and Dogs dataset which had been a Kaggle Challenge in image classification!
---------------------------------------------------------------
На первом курсе этой специализации вы познакомились с TensorFlow и узнали, как с его высокоуровневыми API-интерфейсами выполнять базовую классификацию изображений, а также немного узнали о сверточных нейронных сетях (ConvNets). В этом курсе вы углубитесь в использование ConvNets с реальными данными и узнаете о методах, которые вы можете использовать для повышения производительности ConvNet, особенно при классификации изображений! На этой неделе на первой неделе вы начнете с глядя на гораздо больший набор данных, чем вы использовали до сих пор: набор данных «Кошки и собаки», который был вызовом Kaggle в классификации изображений!

(w1) Learning Objectives: (16.MLg_2c)

● Gain understanding about Keras’ utilities for pre-processing image data, in particular the ImageDataGenerator class
● Develop helper functions to move files around the filesystem so that they can be fed to the ImageDataGenerator
● Learn how to plot training and validation accuracies to evaluate model performance
● Build a classifier using convolutional neural networks for performing cats vs dogs classification
---------------------------------------------------------------
● Получите представление об утилитах Keras для предварительной обработки данных изображений, в частности о классе ImageDataGenerator.
● Разработать вспомогательные функции для перемещения файлов по файловой системе, чтобы их можно было передать в ImageDataGenerator.
● Узнайте, как отображать точность обучения и проверки для оценки производительности модели.
● Создайте классификатор с использованием сверточных нейронных сетей для классификации кошек и собак.

1(w1)-video1: Introduction, A conversation with Andrew Ng (16.MLg_2c)

In the first course, you learned how to use TensorFlow to implement a basic neural network, going up all the way to basic Convolutional Neural Network. In this second course, you go much further. In the first week, you take the ideas you've learned, and apply them to a much bigger dataset of cats versus dogs on Kaggle. Yes so we take the full Kaggle dataset of 25,000 cats versus dogs images. In the last module, we looked at horses and humans, which was about 1,000 images. So we want to take a look at what it's like to train a much larger dataset, and that was like a data science challenge, not that long ago. Now, we're going to be learning that here, which I think is really cool In fact, we have substantially similar ideas as their previous goals, and apply it to much bigger datasets, and hopefully get great results. Yeah, we're hoping for good results. Let's see what the students get as they do some of the assignments with it as well. One of the things that working with a larger dataset, then helps with is over-fitting. So with a smaller dataset, you are at great risk of overfitting; with a larger dataset, then you have less risk of over-fitting, but overfitting can still happen. Pretty cool. Then in week 2, you'll learn another method for dealing with overfitting, which is that TensorFlow provides very easy to use tools for data augmentation, where you can, for example, take a picture of a cat, and if you take the mirror image of the picture of a cat, it still looks like a cat. So why not do that, and throw that into the training set. Exactly. Or for example, you might only have upright pictures of cats, but if the cat's lying down, or it's on its side, then one of the things you can do is rotate the image. So It's like part of the image augmentation, is rotation, skewing, flipping, moving it around the frame, those kind of things. One of the things I find really neat about it, is particularly if you're using a large public dataset, is then you flow all the images off directly, and the augmentation happens as it's flowing. So you're not editing the images themselves directly. You're not changing the dataset. It all just happens in memory. This is all done as part of TensorFlow's Image Generation [inaudible]? Exactly. That they'll learned about it in the second week. Yeah. So then too one of the other strategy, of course for avoiding overfitting, is to use existing models, and to have transfer learning. Yeah. So I don't think anyone has as much data as they wish, for the problems we really care about. So Transfer Learning, lets you download the neural network, that maybe someone else has trained on a million images, or even more than a million images. So take an inception network, that someone else has trained, download those parameters, and use that to bootstrap your own learning process, maybe with a smaller dataset. Exactly. That has been able to spot features that you may not have been able to spot in your dataset, so why not be able to take advantage of that and speed-up training yours. I particularly find that one interesting as you move forward. That to be able to build off of other people's work, the open nature of the AI community, I find is really exciting and that allows you to really take advantage of that and be a part of the community. Standing on the shoulders of giants. I use transfer learning all the time, so TensorFlow lets you do that easily [inaudible] open source. Then finally in the fourth week, Multicast learning. Rather than doing two classes, like horses verses humans, or cats verses dogs, what if you have more than two classes, like class five rock, paper, scissors, that would be three classes, or inception would be 1,000 classes. So that the techniques of moving from two to more than two, be it three or be it a 1,000, are very very similar. So we're going to look at those techniques and we'll look at the code for that. So and we have a rock, paper, scissors example, that you're going to be able to build off of. So in this second course, you take what you learned in the first course, but go much deeper. One last fun thing, Lawrence had seen this coffee mug into AI for everyone in the course, and he asked me to bring it. I love that course, so thank you so much. It's a great course, because it has got everything for people who are beginning; even people who are non-technical, all the way up to experts. So thank you for the mug, but is it okay if I say I spot a sports car in the course as well, would you bring that? I don't have one of those to bring to you. So I'm really excited about this course. Please go ahead and dive into the first of the materials for week 1.
---------------------------------------------------------------
На первом курсе вы узнали, как использовать TensorFlow для реализации базовой нейронной сети, вплоть до базовой сверточной нейронной сети. В этом втором курсе вы идете намного дальше. В первую неделю вы берете изученные идеи и применяете их к гораздо большему набору данных о кошках и собаках на Kaggle. Да, поэтому мы берем полный набор данных Kaggle из 25 000 изображений кошек и собак. В последнем модуле мы рассмотрели лошадей и людей, что составило около 1000 изображений. Итак, мы хотим взглянуть на то, каково это обучать гораздо больший набор данных, и не так давно это было похоже на задачу науки о данных. Теперь мы собираемся изучить это здесь, и я думаю, что это действительно здорово. На самом деле, у нас есть идеи, в значительной степени схожие с их предыдущими целями, и мы применяем их к гораздо большим наборам данных и, надеюсь, получим отличные результаты. Да, мы надеемся на хорошие результаты. Давайте посмотрим, что получают ученики, выполняя с ним некоторые задания. Одна из вещей, которая помогает при работе с большим набором данных, — это чрезмерная подгонка. Таким образом, с меньшим набором данных вы подвергаетесь большому риску переобучения; с большим набором данных у вас меньше риск переобучения, но переоснащение все же может произойти. Довольно круто. Затем на второй неделе вы изучите еще один метод борьбы с переоснащением, заключающийся в том, что TensorFlow предоставляет очень простые в использовании инструменты для увеличения данных, где вы можете, например, сфотографировать кошку, а если взять зеркало образ с изображением кота, он все равно похож на кота. Так почему бы не сделать это и добавить в тренировочный набор. Точно. Или, например, у вас могут быть только вертикальные изображения кошек, но если кошка лежит или лежит на боку, вы можете повернуть изображение. Так что это как часть увеличения изображения, это вращение, перекос, отражение, перемещение по кадру и тому подобное. Одна из вещей, которые я нахожу в этом очень удобным, особенно если вы используете большой общедоступный набор данных, заключается в том, что вы передаете все изображения напрямую, а увеличение происходит по мере их передачи. Таким образом, вы не редактируете сами изображения напрямую. Вы не меняете набор данных. Просто все происходит в памяти. Все это делается как часть генерации изображений TensorFlow [неразборчиво]? Точно. Что они узнают об этом на второй неделе. Ага. Таким образом, одна из других стратегий, конечно же, для предотвращения переобучения, заключается в использовании существующих моделей и трансферном обучении. Ага. Так что я не думаю, что у кого-то есть столько данных, сколько они хотят, для проблем, которые нас действительно волнуют. Итак, Transfer Learning позволяет вам загрузить нейронную сеть, которую, возможно, кто-то еще обучил на миллионе или даже большем миллионе изображений. Итак, возьмите начальную сеть, которую обучил кто-то другой, загрузите эти параметры и используйте их для запуска собственного процесса обучения, возможно, с меньшим набором данных. Точно. Это позволило обнаружить функции, которые вы, возможно, не смогли обнаружить в своем наборе данных, так почему бы не воспользоваться этим и не ускорить обучение. Я особенно нахожу это интересным, когда вы продвигаетесь вперед. Я нахожу, что возможность опираться на работу других людей, открытый характер сообщества ИИ действительно захватывает, и это позволяет вам действительно воспользоваться этим и стать частью сообщества. Стоя на плечах великанов. Я постоянно использую трансферное обучение, так что TensorFlow позволяет вам это легко сделать [неразборчиво] с открытым исходным кодом. Затем, наконец, на четвертой неделе многоадресное обучение. Вместо того, чтобы делать два класса, как лошади против людей или кошки против собак, что, если у вас есть более двух классов, например, пятый класс камень, ножницы, бумага, это будет три класса, или начальный уровень будет 1000 классов. Так что техники перехода от двух к более чем двум, будь то три или будь то 1000, очень и очень похожи. Итак, мы рассмотрим эти методы и код для этого. Итак, у нас есть пример камня, ножниц, бумаги, на основе которого вы сможете построить. Итак, на этом втором курсе вы берете то, чему научились на первом курсе, но идете намного глубже. И последнее забавное обстоятельство: Лоуренс увидел эту кофейную кружку для всех участников курса и попросил меня принести ее. Я люблю этот курс, так что большое спасибо. Это отличный курс, потому что в нем есть все для начинающих; даже люди, которые не являются техническими, вплоть до экспертов. Так что спасибо за кружку, но ничего, если я скажу, что замечу на поле и спортивную машину, ты принесешь ее? У меня нет ни одного из них, чтобы принести вам. Так что я очень взволнован этим курсом. Пожалуйста, продолжайте и погрузитесь в первый из материалов для недели 1

2(w1)-Where to find the notebooks for this course: (16.MLg_2c)

(Где найти тетради для этого курса)
All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You can simply click the Open in Colab badge at the top of the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this
Github repository
under the C2 folder.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/supplement/GXMYv/where-to-find-the-notebooks-for-this-course
If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
scikit-learn==1.0.1
pandas==1.1.5
matplotlib==3.2.2
seaborn==0.11.2
---------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы можете просто щелкнуть значок «Открыть в Colab» в верхней части неоцененных лабораторных работ, в то время как для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом
Репозиторий на гитхабе
в папке C2.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/supplement/GXMYv/где-найти-ноутбуки-для-этого-курса
Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

3(w1)-video2: A conversation with Andrew Ng (16.MLg_2c)

What does it take to download a public dataset off the Internet, like cats verses dogs, and get a neural network to work on it? Data is messy, sometimes you find surprising things like pictures of people holding cats or multiple cats or surprising things in data. In this week, you get to practice with using TensorFlow to deal with all of these issues. Yeah, and it's like, so even for example, you might have some files that are zero length and they could be corrupt as a results. So it's like using your Python skills, using your TensorFlow skills to be able to filter them out. Building a convolutional net to be able to spot things like you mentioned, a person holding it up. So that's some of the things we'll do this week, is by using, and it's still a very clean dataset that we're using with cats versus dogs, but you're going to hit some of those issues. I think you'll learn the skills that you need to be able to deal with other datasets that may not be as clean as this one. Yeah. Sometimes people think that AI is people like Lawrence and me sitting in front of a white board maybe a zen garden outside, talking about the future of humanity. The reality is, there's a lot of data cleaning, and having great tools to help with that data cleaning makes our workflow much more efficient. Definitely. So in this week, you get to practice all that, as well as train a pretty cool neural network to classify cats versus dogs. Please dive in.
---------------------------------------------------------------
Что нужно, чтобы скачать общедоступный набор данных с интернета, такой как "кошка или собака", и получить работающую на нём нейронную сеть? Данные неаккуратные, иногда вы находите удивительные вещи, такие, как картинки людей, которые держат кошку, или несколько кошек сразу, или другие сюрпризы в данных. На этой неделе вы получите практический урок использования TensorFlow для решения всех этих проблем. Да, и может быть даже, что если у вас встречаются файлы нулевой длины, возможно, потому что они повреждены. В таком случае, вы используете навыки в Python, используйте свои навыки в TensorFlow, чтобы отфильтровать такие картинки. Строите свёрточную сеть, чтобы замечать вещи, подобные упомянутым вами: как человек держит кошку. Это одна из тем, которыми мы займёмся на этой неделе, используя пока ещё очень чистый набор данных, мы используем "кошка или собака", — но вы столкнётесь с некоторыми из этих проблем. И, думаю, освоите навыки, необходимые вам, чтобы справиться с другими наборами данных, которые могут быть не такими чистыми. Да. Иногда люди думают, что ИИ — это когда люди, такие как Лоуренс и я, сидят перед маркерной доской, или, может, в дзенском саду, и говорят судьбах человечества. Но реальность в том, что нужно много очистки данных, и если у вас есть хорошие инструменты, помогающие очищать данные, то это сделает наш рабочий процесс намного более эффективным. Несомненно. Итак, на этой неделе вы получите практику в этой области и натренируете довольно крутую нейросеть, которая будет отличать кошек от собак. Погружайтесь в наш курс.

4(w1)-The cats vs dogs dataset: (16.MLg_2c)

In the next video, you'll look at the famous Kaggle Dogs v Cats dataset
https://www.kaggle.com/c/dogs-vs-cats
This was originally a challenge in building a classifier aimed at the world's best Machine Learning and AI Practitioners, but the technology has advanced so quickly, you'll see how you can do it in just a few minutes with some simple Convolutional Neural Network programming.
It's also a nice exercise in looking at a larger dataset, downloading and preparing it for training, as well as handling some preprocessing of data. Even data like this which has been carefully curated for you can have errors -- as you'll notice with some corrupt images!
Also, you may notice some warnings about missing or corrupt EXIF data as the images are being loaded into the model for training. Don't worry about this -- it won't impact your model! :)
---------------------------------------------------------------
В следующем видео вы увидите знаменитый набор данных Kaggle Dogs v Cats.
https://www.kaggle.com/c/dogs-vs-cats
Первоначально создание классификатора, предназначенного для лучших в мире специалистов по машинному обучению и искусственному интеллекту, было сложной задачей, но технология развивалась так быстро, что вы увидите, как это можно сделать всего за несколько минут с помощью простого программирования сверточной нейронной сети.
Это также хорошее упражнение для просмотра большого набора данных, его загрузки и подготовки к обучению, а также предварительной обработки данных. Даже такие данные, которые были тщательно подобраны для вас, могут содержать ошибки — как вы заметите на некоторых поврежденных изображениях!
Кроме того, вы можете заметить некоторые предупреждения об отсутствии или повреждении данных EXIF, поскольку изображения загружаются в модель для обучения. Не беспокойтесь об этом — это не повлияет на вашу модель! :)

5(w1)-video3: Training with the cats vs. dogs dataset (16.MLg_2c)

We've gone from the fashion dataset where the images were small and focused on the subject, to a new situation where we had images of horses and humans and action poses. We use convolutions to help us identify features in the image regardless of their location. This is a nice primer in solving some common data science problems on places like Kaggle. We'll next look at an old competition where you were encouraged to build a classifier to determine cats versus dogs. If you're not familiar with Kaggle, it's where ML challenges are posted often with prizes. Cats versus dogs was a famous one from a few years back. The techniques you've just learned can actually apply to that problem. So let's recap some of the concepts. One of the nice things with TensorFlow and Keras is that if you put your images into named subdirectories, an image generated will auto label them for you. So the cats and dogs dataset you could actually do that and you've already got a massive head start in building the classifier. Then you can subdivide that into a training set and a validation set. Then you can use image generators that appointed at those folders. To use an image generator, you should create an instance of one. If the data isn't already normalized, you can do that with the rescale parameter. You then call the flow from directory to get a generator object. For the training dataset, you will then point at the training directory and then specify the target size. In this case, the images are an all shapes and sizes. So we will resize them to 150 by 150 on the fly. We'll set the batch sizes to be 20. There's 2,000 images, so we'll use a 100 batches of 20 each. Because there are two classes that we want to classify for its still stays as a binary class mode. Similarly for validation, we set up a generator and pointed at the validation directory. We can explore the convolutions and pooling and the journey of the image through them. It's very similar to what you saw with the horses and humans. It has three sets of convolutions followed by pooling. Of course, the image is 150 by 150. Similarly, there's a single neuron with a sigmoid activation on the output. The summary of the layers is very similar to before but note that the size changes. We start with 150 by 150. So the convolution reduces that to 148 by 148. From there, we'll go until we end up with 17 by 17 that we feed into the dense layers. Compilation is as before. Now remember you can tweak the learning rate by adjusting the lr parameter. So now to train, and we can call model.fit generator and pass it the training generator and the validation generator. That's it. As you can see, it's very similar to what you built for horses versus humans. So let's see it in action.
---------------------------------------------------------------
Мы перешли от набора данных "fashion" [с предметами одежды - прим.], где изображения были маленькими, а предмет занимал большую часть кадра, — к новой ситуации, когда у нас есть изображения лошадей и людей в активных позах. Мы используем свёртку, чтобы найти признаки на изображениях, независимо от их местоположения. Это хорошая заготовка для решения некоторых популярных задач data science на площадках вроде Kaggle. А сейчас посмотрим на старый конкурс, в котором нужно было построить классификатор, отличающий кошек от собак. Если вы не знаете, что такое Kaggle, это сайт, на котором размещают конкурсы по машинному обучению, часто с призами. "Кошка или собака" был знаменитым конкурсом несколько лет назад. Приёмы, которые вы только что узнали, можно применить и к этой задачи. Так что давайте освежим некоторые понятия. Одна из замечательных особенностей TensorFlow и Keras — в том, что если вы раскладываете ваши изображения по подкаталогам, генератор изображений автоматически разметит их за вас. Можно поступить так и с "кошками и собаками", и у тогда у вас будет весомый задел для построения классификатора. Дальше вы можете разделить его на тренировочные и валидационные данные. Дальше вы можете запустить генератор изображений, указав ему эти каталоги. Чтобы использовать генератор изображений, вам надо создать объект этого класса. Если данные ещё не нормализованы, вы можете использовать параметр rescale. Затем вы вызываете flow_from_directory, чтобы получить объект генератора. Для тренировочного набора данных укажите на каталог с этим набором и укажете целевой размер. В таком случае, все изображения будут приведены к нужной форме и размеру. То есть, мы отмасштабируем их на лету к размеру 150x150. Мы установим размер группы равным 20. Всего есть 2000 изображений, так что будем использовать 100 групп по 20 элементов каждая. Поскольку мы хотим классифицировать по двум классам, по-прежнему установим бинарный режим. Для валидационного набора мы тем же образом создадим генератор и укажем ему каталог с валидационным набором. Мы можем исследовать свёртки и слияния, и то, как изображение проходит через них. Это очень похоже на то, что вы видели в случае с лошадьми и людьми. В сети есть три слоя свёртки, за каждым следует слой объединения. Конечно, изображения имеют размер 150x150. И так же [как с людьми/лошадьми - прим.] на выходе единственный нейрон с сигмоидной функцией активации. Сводка по слоям очень похожа на то, что было раньше, но обратите внимание, что размер изменился. Мы начинаем со 150x150. Свёртка уменьшает размер до 148x148. И мы продолжаем так, пока не доходим до размера 17x17, который мы отправляем в полносвязные слои. Компиляция происходит так же, как и раньше. Напоминаю, что вы можете настраивать скорость обучения, изменяя параметр lr. Пора тренировать модель, и мы можем вызвать метод model.fit_generator и передать в него генератор тренировочного набора и генератор валидационного набора. Вот и всё. Как видите, это очень похоже на то, что вы делали для лошадей и людей. Давайте посмотрим на это в действии.

6(w1)-Looking at the notebook (Lab 1): (16.MLg_2c)

Now that we’ve discussed what it’s like to extend to real-world data using the Cats vs Dogs dataset, let’s go into a notebook
that shows how to do the challenge for yourself. In the next video, you’ll see a screencast of this notebook in action. You’ll then be able to try it for yourself.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W1/ungraded_lab/C2_W1_Lab_1_cats_vs_dogs.ipynb
---------------------------------------------------------------
Теперь, когда мы обсудили, каково это расширять данные реального мира с помощью набора данных «Кошки против собак», давайте перейдем к блокноту.
который показывает, как сделать вызов для себя. В следующем видео вы увидите скринкаст этого ноутбука в действии. Тогда вы сможете попробовать это сами.

7(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community!: (16.MLg_2c)

Hello!
We’ve created a community for you to:
-Ask for help on assignments and other course content.
-Discuss course topics.
- Share your knowledge with other learners.
- Build your network
- Find out about exciting DeepLearning.AI news, events and competitions!
To go to the community for this course, tick the checkbox below indicating you agree to use the app responsibly, then click on the "Launch App” button.
If you are new to the community, click on the "Launch App" button to create your account and access our community.
We created this User Guide for you.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Be sure to check out the Code of Conduct community guidelines.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Having trouble accessing our community after clicking the “Launch App” button? Fill out this form to explain your issue and we will get back to you.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
We hope to see you in our community soon!
- The DeepLearning.AI team
This course uses a third-party app, [IMPORTANT] Have questions, issues or ideas? Join our Community!, to enhance your learning experience. The app will reference basic information like your name, email, and Coursera ID.
---------------------------------------------------------------
Привет!
Мы создали для вас сообщество, чтобы:
-Попросите помощи в заданиях и другом содержании курса.
-Обсудить темы курса.
- Поделитесь своими знаниями с другими учащимися.
- Создайте свою сеть
- Узнайте о захватывающих новостях, событиях и конкурсах DeepLearning.AI!
Чтобы перейти к сообществу для этого курса, установите флажок ниже, указывающий, что вы согласны использовать приложение ответственно, затем нажмите кнопку «Запустить приложение».
Если вы новичок в сообществе, нажмите кнопку «Запустить приложение», чтобы создать учетную запись и получить доступ к нашему сообществу.
Мы создали это Руководство пользователя для вас.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Обязательно ознакомьтесь с принципами сообщества Кодекса поведения.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Возникли проблемы с доступом к нашему сообществу после нажатия кнопки «Запустить приложение»? Заполните эту форму, чтобы объяснить вашу проблему, и мы свяжемся с вами.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
Надеемся скоро увидеть вас в нашем сообществе!
- Команда DeepLearning.AI
В этом курсе используется стороннее приложение. [ВАЖНО] Есть вопросы, проблемы или идеи? Присоединяйтесь к нашему сообществу!, чтобы улучшить свой опыт обучения. Приложение будет ссылаться на основную информацию, такую ​​как ваше имя, адрес электронной почты и идентификатор Coursera.

8(w1)-video4: Working through the notebook (16.MLg_2c)

The first thing we will do is download the set of images. They're stored as a zip file containing 3,000 images, 2,000 of which we'll use for training, and 1,000 for testing. Once they're downloaded, you'll need access to the underlying operating system of the virtual machine on which this Colab runs. This is available in the OS namespace. This code will unzip the cats and dogs data that you just downloaded, into the directory. In there, the sub-directories will be recreated, because they're stored that were in the zip file. The next thing is for us to set up our directories as variables, so we can point the generators at them. Now, that we have the directories as variables, we can pass them to the os.listdir to take the files from those directories, and load them into Python lists. We can see there's a list of file names like cat253.jpg, etc. On the files tab, we can also inspect the file system and we can see our cats versus dogs folder, within which we have training and validation sub-directories, which each contain cats and dogs directories. The images, of course, are stored in there. If we then count the images in each directory, we can be sure that we have the right amounts of images. As we can see, we have a thousand of each animal in Training and 500 of each in Tests for total of 3000. Next up, we can visualize some of the data, so we can see how diverse it is. This code would set a matplotlib which is a Python library for drawing graphics. This code will pick up some random cats and dogs and draw them in a grid. We can then see once it's drawn that there's a lot of diversity in these images. There's different colors of animal, there's different location within the picture, and there's even sometimes multiple items in the picture, like the lady here holding a cat. We can then run it again to see some more.
This image containing multiple cats is particularly challenging. Okay. Now, let's build our neural network. We'll import TensorFlow, and then we'll define our model. We'll print the summary, and here you can see the output shape of how the image passed through the layers, and gradually reducing in size through the convolution and pooling. Here, is where we compile our model, defining the loss function and the optimizer. Here, is where we set up the two generators, pointing them at the training and validation sub-directories. These contains sub-directories of their own, each with cats and dogs. When I run it, you'll see the printout. It found 2,000 images in two classes, and that's the training, and 1,000 images in two classes, that's the testing.
Now, we'll start the training and we'll watch it progress. It should take 3-3.5 minutes.
When it's done, you can see the accuracy is about 73% and it's not bad. It's not great but it's not bad. Okay. So let's take a look at how the model predicts on some images. So I'm going to choose these five images from my hard drive and upload them. Once they're uploaded, you can see that the classifier gives me a prediction on each. So let's now compare. This first one is really impressive and as you can see, the dog is in a very small part of the image and there's lots of other features like trees, mountains, skies and lakes, and the dog also has its face turned away, but the classifier still got it right. This one is obviously a dog, but again it's partially obscured. You can't see the body. It's just a white mass and the face while pronounced, is also hidden amongst the fur, but it got it right. This one's a bit more obvious, but it's also a very different looking dog than the previous one. The eyes, nose and mouth are all part of a dark patch, but the neural network still recognize the dog. This one's also very impressive. There are two cats in the image and one is mostly hidden, but that didn't confuse the model that correctly recognized the cat here. Strangely enough though, this is the one that the model got wrong. Maybe it's because we can only see one eye, or maybe the sharply defined branches to the left confused the model. So take a look, think about what you would do to go through this workbooks at this point and have some fun with it. Find some images of cats and dogs and upload them to the notebook and get it to classify them, then see if you can find one that you would expect to be easy that the prediction gets wrong. Once you've done that, see if you can edit that image in a way that gets it to work.
---------------------------------------------------------------
Сперва нам нужно скачать набор изображений. Они хранятся как zip-файл, содержащий 3000 изображений, 2000 из которых мы используем для тренировки, а 1000 — для тестирования. Когда они загрузятся, вам потребуется доступ к операционной системе виртуальной машины, на которой запущен Colab. Эта возможность есть в пространстве имён os. Данный код распакует данные "кошка или собака", которые вы только что скачали, в каталог /tmp. Также будут воссозданы подкаталоги, потому что по ним хранилось содержимое zip-файла. Далее нам необходимо задать наши каталоги как значения переменных, чтобы мы могли передать их в генераторы. Теперь, когда у нас есть имена каталогов в виде переменных, мы можем передать их здесь в os.list, чтобы получить списки файлов этих каталогов, загрузив их в списки Python. Как видим, у нас есть список имён файлов вроде cat253.jpg, и т.д.. Можно также посмотреть содержимое файловой системы во вкладке "Files", и в каталоге /tmp мы видим наш каталог "кошка или собака", внутри которого есть подкаталоги с тренировочными и валидационными данными, в каждом из которых есть каталоги "cats" и "dogs". Изображения, разумеется, хранятся в них. Если мы подсчитаем изображения в каждом каталоге, мы убедимся, что у нас нужное количество изображений. Как мы видим, у нас по тысяче изображений каждого животного в тренировочном наборе, и по 500 в тестовом, а всего 3000. Дальше мы можем визуализировать часть данных, чтобы увидеть, насколько они отличаются. Этот код настраивает matlpotlib — библиотеку Python для вывода графиков. Этот код выберет несколько случайных кошек и собак и выведет их в таблице. И тогда мы увидим, что изображения весьма разнообразны. У животных разный цвет, они находятся в разных местах кадра, и иногда даже на изображении есть несколько персонажей, например, женщина, держащая кошку. Затем мы можем запустить код ещё раз, чтобы увидеть ещё немного изображений.
Это изображение, на котором несколько кошек, — представляет особую сложность. Хорошо, теперь давайте строить нашу нейросеть. Мы импортируем TensorFlow и определим нашу модель. Мы выведем на экран сводку по модели, и в ней видно, как выходной размер по мере того, как изображение будет проходить через слои, постепенно уменьшается в размерах, проходя через свёртки и объединение. Здесь мы компилируем нашу модель, определяя функцию потерь и оптимизатор. Здесь мы настраиваем два генератора, указывая им подкаталоги с тренировочным и валидационным наборами. В каждом из них есть свои подкаталоги cats и dogs. Когда я запущу код, посмотрите, что он выведет. Он нашёл 2000 изображений двух классов, это тренировочный набор, и 1000 изображений двух классов — это тестовый набор. Теперь мы можем произвести обучение. В этот раз вместо того, чтобы использовать model.fit, мы снова используем model.fit_generator, потому что наши источники данных — генераторы. И вы видите, как мы их туда передаём. Теперь запустим обучение и будем следить за прогрессом. Обучение должно занять 3-3,5 минуты. Когда оно закончится, вы увидите, что точность около 73%, и это неплохо. Не слишком хорошо, но и неплохо. Хорошо, давайте теперь взглянем на предсказания модели на некоторых изображениях. Итак, я выберу эти пять изображений с моего жёсткого диска и загружу их. Когда они загрузятся, вы увидите, что классификатор даёт предсказания для каждого из них. Давайте теперь сравним. Мы видим, что для первого изображения предсказание явно неверное, но давайте сейчас посмотрим на каждое изображение, чтобы понять, можно ли сравнить результаты. Первое изображение действительно впечатляющее, потому что, как видите, собака занимает очень маленькую часть изображения, и на нём много разного: деревья, горы, небо, озеро, — а также собака отвернулась от нас, но классификатор всё равно дал верный ответ. Это определённо собака, но, опять-таки, она частично скрыта. Вы не видите тело. Это просто белое нечто, а морда, хотя и отчётливая, тоже маскируется шерстью, но результат здесь верный. Здесь всё несколько очевиднее, но при этом на вид сильно отличается от предыдущей собаки. Глаза, нос и рот — всё это части тёмного пятна, но нейросеть всё равно распознаёт собаку. Это изображение тоже очень впечатляющее. На нём две кошки, и одна почти скрыта, но это не смущает модель, которая корректно распознаёт кошку. Тем не менее, довольно удивительно, что на этом изображении модель ошибается. Возможно, потому что видно лишь один глаз, а может, резко очерченные ветки слева сбивают модель с толку. Итак, поизучайте, подумайте, что вы ещё можете сделать с этим блокнотом, и позанимайтесь с ним немного. Найдите несколько изображений кошек и собак, загрузите их в блокнот, и классифицируйте, а затем посмотрите, сможете ли вы найти такую картинку, чтобы она казалась простой, но предсказание оказалось бы ложным. Когда найдёте — посмотрите, получится ли у вас отредактировать это изображение так, чтобы модель заработала.

9(w1)-What you'll see next!: (16.MLg_2c)

In the last video, you saw a screencast of the notebook that shows how to build a classifier for Cats vs Dogs. You saw how, in some cases, it didn’t classify one cat correctly, and we asked you to try to figure out how you might fix it. In the next video, you’ll see one solution to this.
---------------------------------------------------------------
В последнем видео вы видели скринкаст блокнота, в котором показано, как построить классификатор для кошек против собак. Вы видели, как в некоторых случаях он неправильно классифицировал одну кошку, и мы попросили вас попытаться выяснить, как вы могли бы это исправить. В следующем видео вы увидите одно решение этой

10(w1)-video5: Fixing through cropping (16.MLg_2c)

Did you find a solution? Well, of course yours might be different from mine but let me show you what I did in the case of the cat my model thought was a dog. So let's go back to the notebook, and we'll run the code. I'll upload this image to see how it classifies. It's a crop of the cats, and lo and behold, it classifies as a cat. Let's open it, and compare it to the original image, and we'll see that just by cropping I was able to get it to change its classification. There must have been something in the uncropped image that matched features with a dog. Now I thought that was a very interesting experiment, didn't you? Now what do you think the impact of cropping might've had on training? Would that have trained the model to show that this was a cat better than an uncropped image. That's food for thought, and something to explore in the next lesson but first let's go back to the workbook.
---------------------------------------------------------------
Вы нашли решение? Конечно, ваше решение может отличаться от моего, но позвольте мне показать вам, что я делал в том случае, когда моя модель принимала кошку за собаку. Давайте вернёмся к блокноту и запустим код. Я загружаю это изображение, чтобы увидеть, как оно классифицируется. Это фрагмент изображения с кошкой и, как вы видите, классифицируется оно как кошка. Давайте откроем изображение и сравним с изначальным, и мы видим, что просто обрезав его, я смог изменить результат классификации. Должно быть что-то в необрезанном изображении, отвечавшее признакам собаки. И я думаю, что это был очень интересный эксперимент, не так ли? А что вы думаете о возможном влиянии обрезки на тренировку модели? Было бы лучше тренировать модель, указав этот вариант с кошкой, а не полное изображение? Это тема для размышлений и исследований на следующем уроке, но сперва вернёмся к блокноту.

11(w1)-video6: Visualizing the effect of the convolutions (16.MLg_2c)

Okay, in the previous video you took a look at a notebook that trained a convolutional neural network that classified cats versus dogs. Now let's take a look at how that worked.
Let's return to the notebook and take a look at the code that plots the outputs of the convolutions in max pooling layers. The key to this is understanding the model.layers API, which allows you to find the outputs and iterate through them, creating a visualization model for each one.
We can then load a random image into an array and pass it to the predict method of the visualization model.
The variable to keep an eye on is display_grid which can be constructed from x which is read as a feature map and processed a little for visibility in the central loop.
We'll then render each of the convolutions of the image, plus their pooling, then another convolution, etc.
You can see images such as the dog's nose being highlighted in many of the images on the left.
We can then run it again to get another random image. And while at first glance this appears to be a frog, if you look closely it's a Siamese cat with a dark head and dark paws towards the right of the frame. It's hard to see if any of the convolutions lock down on a feature. Except maybe the synonymous upright tail of the cat, we can see that vertical dark line in a number of the convolutions.
And let's give it one more try. We can see what's clearly a dog, and how the ears of the dog are represented very strongly. Features like this moving through the convolutions and being labeled as doglike could end up being called something like a floppy ear detector.
---------------------------------------------------------------
Итак, в предыдущем видео вы ознакомились с блокнотом, который тренировал свёрточную нейронную сеть, отличавшую кошек от собак. Давайте теперь посмотрим, как именно она работает.
Вернёмся к блокноту и посмотрим на код, отображающий выходы свёрток в объединяющие слои. Ключ к нему — в понимании программного интерфейса model.layers, который даёт вам возможность найти выходы [всех слоёв - прим.] и перечислять их, создавая для каждого модель визуализации.
Следите за переменной display_grid, которая создаётся из x, считываемого как карта признаков, и немного обрабатывается в самом вложенном цикле для наглядности.
Затем мы отображаем каждую из свёрток изображения, плюс слои объединения, затем следующая свёртка, и т.д..
Вы видите, что изображения, подобные собачьему носу, подсвечиваются на многих изображениях слева.
Мы можем запустить код ещё раз, чтобы взять другое случайное изображение. И хотя на первый взгляд это кажется лягушкой, но если вы внимательно присмотритесь, это сиамская кошка с тёмной головой и тёмными лапами в правой части кадра. Сложно увидеть, фиксирует ли признаки какая-либо из свёрток. Кроме, разве что, кошачьего хвоста справа вверху: мы видим тёмную вертикальную линию в череде свёрток.
Давайте сделаем ещё одну попытку. Мы явно видим собаку, и то, что собачьи уши отчётливо присутствуют. Таким признакам, проходящим сквозь свёртки и маркирующим сходство с собакой, можно даже дать название, вроде "индикатора висячих ушей".
Мы можем загрузить случайное изображение в виде массива, и передать его в метод predict модели визуализации.

12(w1)-video7: Looking at accuracy and loss (16.MLg_2c)

Before we go, let's have a quick look at plotting the learning history of this model. The object has training accuracy and loss values as well as validation accuracy and validation loss values. So let's iterate over these and plot them. Now, if you look closely, we didn't just call model.fit, we said history equals model.fit. So we now have a history object that we can query for data. Here you can see I'm using the same history object, and I'm calling its history property passing at ACC which gets me the model accuracy. When I run it and plot the training and validation accuracy, we can see that my training went towards one while my validation leveled out into 0.7 to 0.75 range. That shows that my model isn't bad, but I didn't really earn anything after just two epochs. It fits the training data very well with the validation data needed work. These results are borne out in the loss where we can see that after two epochs, my training loss went down nicely, but my validation loss climbed. So as it is, my model is about 75 percent accurate-ish after two epochs, and I don't really need to train any further. Remember also that we just used a subset of the full data. Using the entire dataset would likely yield better results. But before we do that, let's look at a few other options, and we'll do that in the next lesson.
---------------------------------------------------------------
Перед тем, как продолжить, давайте быстро взглянем на график истории обучения этой модели. В объекте истории хранятся точность и значение потерь как на тренировочном наборе, так и на валидационном. Давайте пройдёмся по этим значениям и построим их график. Если присмотреться, мы не просто вызвали model.fit, мы написали: history = model.fit(...) Так что у нас есть объект истории, к которому мы можем обратиться за данными. Как вы видите, я использую тот же самый объект истории, и я обращаюсь к его свойству history, передавая ключ acc, что даёт мне точность модели. Когда я запускаю код и вывожу график точности на тренировочном и валидационном наборах, видно, что точность на тренировочном наборе стремится к 1, а на валидационном остаётся между 0.7 и 0.75. Это говорит о том, что моя модель неплоха, но я не получаю никаких результатов уже после двух эпох обучения. Модель хорошо соответствует тренировочным данным, но над валидационными нужно работать. Эти выводы также видны на графике функции потерь: видно, как после двух эпох значение функции на тренировочном наборе быстро снижается, а на валидационном потери растут. Итак, моя модель точна на 75% после двух эпох, и дальнейшая тренировка ничего не даёт. Теперь вспомним, что мы использовали лишь подмножество всех данных. Использование полного набора, вероятно, даст лучшие результаты. Перед тем как приступить, давайте обратим внимание на некоторые другие варианты, поговорим о них на следующем уроке.

13(w1)-What have we seen so far?: (16.MLg_2c)

At the end of the last video, you saw how to explore the training history and discovered an interesting phenomenon: Even though the training data set’s accuracy went very high, we saw that after only a few epochs, the validation set leveled out. This is a clear sign that we are overfitting again. Using more data should help with this, but there are some other techniques that you can use with smaller data sets too. And we’ll see them in next week’s lesson!
---------------------------------------------------------------
В конце последнего видео вы увидели, как исследовать историю обучения, и обнаружили интересное явление: несмотря на то, что точность набора данных для обучения стала очень высокой, мы увидели, что всего через несколько эпох проверочный набор выровнялся. Это явный признак того, что мы снова переоснащаемся. Использование большего количества данных должно помочь в этом, но есть некоторые другие методы, которые вы можете использовать и с меньшими наборами данных. И мы увидим их на уроке на следующей неделе!

14(w1)- Week 1 Quiz: (16.MLg_2c)

1) What does flow_from_directory give you on the ImageDataGenerator?:
1. The ability to easily load images for training
2. The ability to pick the size of training images
3. The ability to automatically label images based on their directory name
4. All of the above (+)
2) If my Image is sized 150x150, and I pass a 3x3 Convolution over it, what size is the resulting image?:
1. 450x450
2. 153x153
3. 150x150(-)
4. 148x148(+)
3) If my data is sized 150x150, and I use Pooling if size 2X2, what size will the resulting image be?:
1. 300x300
2. 148x148
3. 149x149
4. 75x75 (+)
4) If I want to view the history of my training, how can I access it?:
1. Create a variable 'history and assign it to the return of model.fit or model.fit_generator (+)
2. Use a model.fit_generator (-)
3. Pass the parameter 'history=True' to the model.fit
4. Download the model and inspect it
5) What's the name of the API that allows you to inspect the impact of convolutions in the images?:
1. The model.convolutions API
2. The model.images API
3. The model.pools API
4. The model.layers API (+)
6) When exploring the graphs, the loss levelled out at about .75 after 2 epochs, but the accuracy climbed close to 1.0 after 15 epochs. What's the significance of this?:
1. There was no point training after 2 epochs, as we overfit to the validation data
2. There was no point training after 2 epochs, as we overfit to the taring data (+)
3. A bigger training set would give us better validation accuracy (-)
4. A bigger validation set would give us better training accuracy
7) Why is the validation accuracy a better indicator of model performance than training accuracy?:
1. It isn't, they're equally valuable
2. There's no relationship between them
3. The validation accuracy is based on images that the model hasn't been trained with, and this a better indicator of how the model will perform with new images(+)
4. The validation dateset is smaller, and this less accurate at measuring accuracy, so its performance isn't as important
8)Why is overfitting more likely to occur on smaller datasets?:
1. Because in a smaller dataset, your validation data is more likely to look like your training data.
2. Because there isn't enough data to activate all the convolutions or neurons
3. Because with less data, the training will take place more quickly, and some features may be missed
4. Because there's less likelihood of all possible features being encountered in the training process(+)

15(w1)-video8: Week 1 Wrap up (16.MLg_2c)

So you've now reached the end of week one. Congratulations. What I find really inspiring about this particular week was that what you've just done with the cats versus dogs datasets as a Kaggle data science challenge, not that long ago was really only available to the top view, the best researchers at the best universities. But now, thanks to the explosion in compute power, open datasets such as this one, and things such as TensorFlow, you're actually able to do this by yourself, on your own home computer. I find that really inspiring and really exciting. So thank you and get ready for week two.
---------------------------------------------------------------
Итак, вы дошли до конца первой недели. Поздравляю! Я считаю действительно вдохновляющим на этой неделе то, что вы справились с определением кошек и собак на наборе данных с соревнования Kaggle, а ведь это совсем недавно было доступно лишь верхушке, лучшим исследователям из лучших университетов. Но сейчас, благодаря взрывному росту вычислительной мощности, общедоступности наборов данных, таких, как этот, и вещам, подобным TensorFlow, — вы можете сделать это сами, на собственном домашнем компьютере. Я считаю это действительно вдохновляющим и захватывающим. Спасибо вам, и готовьтесь ко второй неделе.

16(w1)-Lecture Notes Week 1: (16.MLg_2c)

he lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
opyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes.
https://www.deeplearning.ai
You may make copies of these slides and use or distribute them for educational purposes as long as you cite
DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторском праве
Эти слайды распространяются по лицензии Creative Commons.
DeepLearning.AI делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях.
https://www.deeplearning.ai
Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы цитируете
DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные сведения о лицензии см.
https://creativecommons.org/licenses/by-sa/2.0/legalcode

17(w1)-Assignment Troubleshooting Tips: (16.MLg_2c)

(Советы по устранению неполадок с заданиями)
Here are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
1. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
2. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by following the instructions her. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/have-questions-meet-us-on-discourse
---------------------------------------------------------------
Ниже приведены некоторые общие рекомендации перед отправкой заданий по этому курсу. Пожалуйста, имейте это в виду не только для задания этой недели, но и для следующих:
1. Пожалуйста, не изменяйте код вне тегов START CODE HERE и END CODE HERE. Ваше решение должно быть размещено только между этими маркерами, чтобы гарантировать успешное оценивание. Изменение параметров функции и других тестовых ячеек, скорее всего, приведет к поломке оценщика. Если вы хотите поэкспериментировать с ними, вы можете сделать это после того, как успешно пройдете задание.
2. Если у вас есть дополнительные вопросы, создайте тему в сообществе Discourse, а не на дискуссионных форумах Coursera. Вы можете присоединиться, следуя ее инструкциям. Вы получите помощь там быстрее, потому что несколько наставников и ваших однокурсников следят за сообщениями. Просто убедитесь, что тема создана в правильной категории курса.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/have-questions-meet-us-on-discourse

18(w1)-Programming Assignment: Cats vs Dogs: (16.MLg_2c)

Instructions
This week, you explored a reduced version of the Cats v Dogs dataset and used it to train a convolutional neural network. You saw that it overfit very quickly, despite great results with the training set. One solution to overfitting is to use more data for both training and validation, and that’s this week’s exercise -- to build a classifier using the full Cats v Dogs dataset of 25k images!
Note again that when loading the images, you might get warnings about EXIF data being missing or corrupt. Don't worry about this -- it is missing data in the images, but it's not visual data that will impact the training.
Let's start building a classifier using the full Cats v Dogs dataset of 25k images.
---------------------------------------------------------------
инструкции
На этой неделе вы изучили сокращенную версию набора данных Cats v Dogs и использовали ее для обучения сверточной нейронной сети. Вы видели, что он очень быстро переобучается, несмотря на отличные результаты с тренировочным набором. Одним из решений переобучения является использование большего количества данных как для обучения, так и для проверки, и это упражнение на этой неделе — создать классификатор, используя полный набор данных «Кошки против собак» из 25 000 изображений!
Еще раз обратите внимание, что при загрузке изображений вы можете получить предупреждения об отсутствии или повреждении данных EXIF. Не беспокойтесь об этом — на изображениях отсутствуют данные, но это не визуальные данные, которые повлияют на обучение.
Давайте начнем создавать классификатор, используя полный набор данных Cats v Dogs из 25 000 изображений.
---------------------------------------------------------------
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
(Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.)
This notebook is hosted on Github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
(Эта записная книжка размещена на Github, поэтому для сохранения любых изменений вам необходимо создать ее копию на своем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».)
---------------------------------------------------------------
You should upload two files:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
create_train_val_dirs
split_data
train_val_generators
create_model
- The training history of your model (a file with .pkl extension) which will be used to grade the accuracy of your model.
---------------------------------------------------------------
Вы должны загрузить два файла:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
create_train_val_dirs
split_data
train_val_generators
create_model
- История обучения вашей модели (файл с расширением .pkl), которая будет использоваться для оценки точности вашей модели.
---------------------------------------------------------------
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.
---------------------------------------------------------------
If you have any questions about the assignments in this course, kindly ask for assistance in our community. If you haven't yet,lease click here and follow the instructions so you can join!
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community-on-discourse
---------------------------------------------------------------
Если у вас есть какие-либо вопросы о заданиях в этом курсе, пожалуйста, обратитесь за помощью в наше сообщество. Если вы еще этого не сделали, нажмите здесь и следуйте инструкциям, чтобы присоединиться!
---------------------------------------------------------------
How to submit
When you're ready to submit, you can upload files for each part of the assignment on the "My submissions" tab.
---------------------------------------------------------------
Как отправить
Когда вы будете готовы отправить, вы можете загрузить файлы для каждой части задания на вкладке «Мои материалы».

=======

10(w3)-video6: Walking through convolutions (15.MLg_1c)

(Прогулка по сверткам, извилинам)
In the previous lessons, you saw the impacts that convolutions and pooling had on your networks efficiency and learning, but a lot of that was theoretical in nature. So I thought it'd be interesting to hack some code together to show how a convolution actually works. We'll also create a little pooling algorithm, so you can visualize its impact. There's a notebook that you can play with too, and I'll step through that here. Here's the notebook for playing with convolutions. So first, we'll set up our inputs and in particular, import the misc library from SciPy. Now, this is a nice shortcut for us because misc.ascent returns a nice image that we can play with, and we don't have to worry about managing our own. Matplotlib contains the code for drawing an image and it will render it right in the browser with Colab. Here, we can see the ascent image from SciPy. Next up, we'll take a copy of the image, and we'll add it with our homemade convolutions, and we'll create variables to keep track of the x and y dimensions of the image. So we can see here that it's a 512 by 512 image. So now, let's create a convolution as a three by three array. We'll load it with values that are pretty good for detecting sharp edges first. Here's where we'll create the convolution. We iterate over the image, leaving a one pixel margin. You'll see that the loop starts at one and not zero, and it ends at size x minus one and size y minus one. In the loop, it will then calculate the convolution value by looking at the pixel and its neighbors, and then by multiplying them out by the values determined by the filter, before finally summing it all up. Let's run it. It takes just a few seconds, so when it's done, let's draw the results. We can see that only certain features made it through the filter. I've provided a couple more filters, so let's try them. This first one is really great at spotting vertical lines. So when I run it, and plot the results, we can see that the vertical lines in the image made it through. It's really cool because they're not just straight up and down, they are vertical in perspective within the perspective of the image itself. Similarly, this filter works well for horizontal lines. So when I run it, and then plot the results, we can see that a lot of the horizontal lines made it through. Now, let's take a look at pooling, and in this case, Max pooling, which takes pixels in chunks of four and only passes through the biggest value. I run the code and then render the output. We can see that the features of the image are maintained, but look closely at the axes, and we can see that the size has been halved from the 500's to the 250's. For fun, we can try the other filter, run it, and then compare the convolution with its pooled version. Again, we can see that the features have not just been maintained, they may have also been emphasized a bit. So that's how convolutions work. Under the hood, TensorFlow is trying different filters on your image and learning which ones work when looking at the training data. As a result, when it works, you'll have greatly reduced information passing through the network, but because it isolates and identifies features, you can also get increased accuracy.
Have a play with the filters in this workbook and see if you can come up with some interesting effects of your own.
---------------------------------------------------------------
На предыдущих занятиях вы видели, как повлияли свёртки и пулинг на эффективность сети и обучение, но многое из этого имело теоретический характер. Поэтому я подумал, что было бы интересно нам вместе поиграть с кодом, чтобы показать, как на самом деле работают свертки. Мы также создадим небольшой алгоритм пулинга, так что вы сможете увидеть его воздействие. Вы тоже сможете поиграть с блокнотом, а я сейчас пройдусь по нему пошагово. Вот блокнот, чтобы поиграться со свёртками. Здесь используются несколько Python-библиотек, с которыми вы, возможно незнакомы — например, cv2. В нём также используется Matplotlib, которую мы использовали ранее. Если вы не использовали их — не страшно, они достаточно интуитивно понятны для выполнения этой задачи, и их очень легко изучить. Итак, сначала мы настроим все импорты, в частности, импортируем библиотеку misc из SciPy. Это здорово сэкономит нам время, поскольку misc.ascent() возвращает хорошее изображение, с которым можно играться, и нам не придётся заниматься подготовкой своего. Библиотека Matplotlib содержит код для отрисовки изображений, и она отрисует его прямо в браузере с Colab. Здесь мы видим изображение ascent из SciPy. Следующим шагом мы сделаем копию изображения, дополним его нашими самодельными свёртками, и создадим переменные для отслеживания размеров изображения x и y. Мы видим, что это изображение имеет размер 512х512. Итак, давайте создадим свертку как массив 3х3. Мы заполняем его значениями, хорошо подходящими для обнаружения резких краёв. А здесь мы будем создавать свертки. Мы итерируемся по всему изображению, оставляя поля в 1 пиксел. Вы видите, что цикл начинается с 1, а не с 0, а завершается на size_x-1, и size_y-1. В этом цикле вычисляется значение свёртки: берутся значения пикселя и его соседей, и умножаются на значения, заданные фильтром, и результаты затем суммируются. Давайте запустим этот код. Это займёт всего несколько секунд, и когда будет готово — отобразим результаты. Мы видим, что лишь определённые признаки прошли сквозь фильтр. У меня есть ещё парочка фильтров, так что давайте попробуем их. Этот фильтр отлично справляется с выявлением вертикальных линий. Поэтому, когда я запущу его и отображу результаты, мы увидим, что вертикальные линии на изображении прошли через него. Это действительно здорово, потому что они не просто идут сверху вниз, а они вертикальны в перспективе, внутри перспективы самого изображения. Подобным образом, вот этот фильтр хорошо работает для горизонтальных линий. И когда я запущу его, и затем выведу результаты, мы видим, что многие горизонтальные линии прошли через него. Теперь давайте посмотрим на пулинг, а в нашем случае, это MaxPooling, при котором пикселы берутся порциями по 4, а пропускаются только наибольшие значения. Я запускаю код, и выводится результат. Мы видим, что признаки на изображении сохранились, но посмотрев внимательно на оси, мы видим, что размер уменьшился наполовину с 500 до 250. Ради забавы мы можем попробовать другой фильтр, выполнить его и затем сравнить свёртку с результатом пулинга над ней. Опять же мы видим, что признаки не просто сохранились, они также стали немного более выраженными. Вот так работают свёртки. Под капотом TensorFlow пробует различные фильтры на вашем изображении и изучает, какие из них работают, глядя на учебные данные. В результате, при его работе сильно сократится объём информации, пропускаемой через сеть. Однако т.к. это изолирует и выделяет признаки, можно также получить прирост точности. Поиграйтесь с фильтрами в этой рабочей тетради, и посмотрите, найдёте ли вы самостоятельно какие-нибудь интересные эффекты.

10(w3)- Experiment with filters and pools (Lab 2): (15.MLg_1c)

( Экспериментируйте с фильтрами и пулами)
Here is the notebook to try some convolutions. Let us know if you come up with any interesting filters of your own!
As before, spend a little time playing with this notebook. Try different filters, and research different filter types. There's some fun information about them here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W3/ungraded_labs/C1_W3_Lab_2_exploring_convolutions.ipynb
https://lodev.org/cgtutor/filtering.html
---------------------------------------------------------------
Вот блокнот, чтобы попробовать некоторые извилины. Дайте нам знать, если вы придумаете какие-нибудь интересные фильтры!
Как и прежде, потратьте немного времени, играя с этим блокнотом. Попробуйте разные фильтры и исследуйте разные типы фильтров. Есть забавная информация о них здесь.

11(w3)- Week 3 Quiz: (15.MLg_1c)

1) How do Convolutions improve image recognition?:
1.They make the image clearer
2. They make the image smaller
3. They make processing of images faster
4. They isolate features in images (+)
2) What does the Pooling technique do to the images?:
1. Combines them
2. Makes them sharper
3. Isolates features in them
4. Reduces information in them while maintaining some features (+)
3) True or False. If you pass a 28x28 image through a 3x3 filter the output will be 26x26?:
True (+)
4) After max pooling a 26x26 image with a 2x2 filter, the output will be 56x56?:
False (+)
5) How does using Convolutions in out Deep neural network impact training?:
1. It does not affect training
2. Its impact will depend on other factors (+)
3. It makes it faster
4. It makes is slower

11(w3)- Lecture Notes Week 3: (15.MLg_1c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах Эти слайды распространяются по лицензии Creative Commons.
DeepLearning.AI делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

12(w3)-Weekly Assignment: (15.MLg_1c)

Improve MNIST with convolutions (Улучшить MNIST с помощью сверток)
Ok, now it’s time for this week’s assignment. In the class, you learned how to enhance the Fashion MNIST neural network with convolutions to make it more accurate. Now it’s time to revisit the handwriting MNIST dataset from last week, and see if you can enhance it with convolutions.
To submit your Jupyter Notebook for grading, please click the Submit Assignment button while in the notebook.
---------------------------------------------------------------
Хорошо, теперь пришло время для задания этой недели. На занятии вы узнали, как улучшить нейронную сеть Fashion MNIST с помощью сверток, чтобы сделать ее более точной. Теперь пришло время вернуться к набору данных рукописного ввода MNIST с прошлой недели и посмотреть, сможете ли вы улучшить его с помощью сверток.
Чтобы отправить блокнот Jupyter на оценку, нажмите кнопку «Отправить задание» в блокноте.
---------------------------------------------------------------
IMPORTANT FOR SUCCESSFUL GRADING:
- Don't forget to save your notebook before submitting!
- Don't delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не забудьте сохранить блокнот перед отправкой!
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

NEXT week_4 (15.MLg_1c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/:

(w4) Using Real-world Images (15.MLg_1c)

(Использование изображений реального мира)
(Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning)
---------------------------------------------------------------
Video: 27 minutes
Self-study: 2,23 hour
Graded tasks (Tasks to be assessed): 2

(w4) Introduction: (15.MLg_1c)

Last week you saw how to improve the results from your deep neural network using convolutions. It was a good start, but the data you used was very basic. What happens when your images are larger, or if the features aren’t always in the same place? Andrew and Laurence discuss this to prepare you for what you’ll learn this week: handling complex images!
---------------------------------------------------------------
На прошлой неделе вы увидели, как улучшить результаты вашей глубокой нейронной сети с помощью сверток. Это было хорошее начало, но данные, которые вы использовали, были очень простыми. Что происходит, когда ваши изображения больше или если функции не всегда находятся в одном и том же месте? Эндрю и Лоуренс обсуждают это, чтобы подготовить вас к тому, чему вы научитесь на этой неделе: работе со сложными изображениями!

(w4) Learning Objectives: (15.MLg_1c)

● Reflect on the possible shortcomings of your binary classification model implementation
● Execute image preprocessing with the Keras ImageDataGenerator functionality
● Carry out real life image classification by leveraging a multilayer neural network for binary classification
---------------------------------------------------------------
● Подумайте о возможных недостатках реализации вашей модели бинарной классификации.
● Выполнение предварительной обработки изображений с помощью функции Keras ImageDataGenerator.
● Выполняйте классификацию реальных изображений, используя многослойную нейронную сеть для бинарной классификации.

1(w4)-video1: A conversation with Andrew Ng (15.MLg_1c)

So, there we saw that the classifier that we built for classifying fashion, like using convolutions were able to make it more efficient and to make it more accurate. I thought that was really, really cool, but it's still very limited in the scenario because all of our images are 28 by 28 and the subject is actually centered. And while it's a fabulous dataset for learning, it's like when we start getting into real-world images and complex images that maybe we need to go a little bit further. What do you think? I think it's really cool that taking the core idea of a confinet allows you to implement an algorithm to confine not just handbags right in the middle of the image but anywhere in the image, so it could be carried by someone on the left or the right of a much bigger and, say, a one-megapixel image. This is 1000 by 1000 pixels. Also for many applications rather than using grayscale, want to use color images- All right. And the same core ideas but with a bigger dataset, bigger images in similar labels lets you do that. All right. So, the technique that you're learning in this, is really really helping you to be able to succeed in these more real-world scenarios. So, I know you've been working on a dataset on horses- Yeah. And humans. Yeah, that's been a lot of fun. I've been working on a dataset that's a number of images of horses and they're moving around the image and they're in different poses, and humans in the same way and diverse humans male, female, different races, that kind of thing to see if we can build a binary classifier between the two of them. But what was really interesting about this is that they're all computer-generated images, but we can use them to classify real photos. I had a lot of fun with that. So, I think there'll be a fun exercise for you to work on as well. And if you're ever wondering of these algorithms you're learning whether this is the real stuff, the algorithims you're learning is really the real stuff that is used today in many commercial applications. For example, if you look at the way a real self-driving car today uses cameras to detect other vehicles or pedestrians to try to avoid them, they use convolutional neural networks for that part of the task, very similar to what you are learning. And in fact, in other contexts, I've heard you speak about using a convolutional neural network. To take a picture, for example. Yeah, we can take a picture of a crop and try to tell if it has a disease coming. So, that was really cool. Oh, thank you, thank you. That's really fun. So, in the next video, you'll learn how to apply convolutional neural networks to these much bigger and more complex images. Please go on to the next video.
---------------------------------------------------------------
Мы увидели, что классификатор, который мы создали для классификации одежды с использованием свёрток, смог сделать классификацию эффективнее и точнее. Я думал, что это очень, очень круто, но всё ещё очень ограниченно в сценариях применения, т.к. все наши изображения имеют размерность 28х28, а объект расположен по центру. И хотя это потрясающий набор данных для изучения, но когда мы переходим к реальным изображениям, к сложным изображениям, то нам, возможно, нужно пойти чуть дальше. Что думаете? Я думаю — это действительно здорово, что основная идея свёрточной сети позволяет вам реализовать алгоритм, не ограниченный одними лишь сумочками, находящимися точно по центру изображения — а чтоб они были где угодно на картинке. Чтобы их можно было перемещать влево или вправо на гораздо большем изображении — скажем, в 1 мегапиксель. Это 1000х1000 пикселов. Также для многих приложений вместо полутоновых изображений хочется использовать цветные. Верно. И те же основные принципы, но с бо́льшим набором данных, бо́льшими по размеру изображениями и теми же метками — позволят вам это сделать. Всё верно. Тот метод, которому вы здесь учитесь, очень поможет вам суметь достичь успеха в реальных сценариях. Я знаю, что вы работаете над набором данных с лошадьми. >> Да. и людьми. Да, это очень увлекательно. Я работаю над набором данных. Это набор изображений лошадей, которые двигаются по изображению, они находятся в разных позах. И люди точно так же. Это разные люди: мужчины, женщины, разной расы, и так далее, — для того, чтобы посмотреть: сможем ли мы построить бинарный классификатор между людьми и лошадьми. Но что действительно было интересно — что все эти изображения были сгенерированы компьютером, но мы можем использовать их для классификации реальных фотографий. Я получил от этого массу удовольствия. Я думаю, что у нас также будет интересное упражнение и для вас. И если вы когда-нибудь задумывались, являются ли алгоритмы, которые вы изучаете, чем-то практичным, То я скажу: алгоритмы, которые вы изучаете — практичны, и используются сегодня во многих коммерческих приложениях. Например, если вы посмотрите на то, как реальные автопилоты на автомобилях используют камеры для обнаружения других транспортных средств или пешеходов, чтобы не столкнуться с ними, — то там для этой задачи применяются свёрточные нейронные сети, очень похожие на те, что вы изучаете. И на самом деле, в других областях, я слышал, как вы говорили об использовании свёрточной нейронной сети для того, чтобы, например, сделать снимок... Да, мы можем сделать снимок урожая и попытаться сказать, приближается ли болезнь. Это очень классно. О, спасибо, спасибо. Это действительно классно. В следующем видео вы научитесь применять свёрточные нейронные сети для куда более крупных и сложных изображений. Приглашаем вас перейти к следующему видео.

2(w4)-Explore an impactful, real-world solution: (15.MLg_1c)

(Узнайте об эффективном реальном решении)
As Andrew and Laurence discussed, the techniques you’ve learned already can apply to complex images, and you can start solving real scenarios with them. They discussed how it could be used, for example, in disease detection with the Cassava plant, and you can see a video demonstrating that here. Once you’ve watched that, move onto the next lesson!
https://www.youtube.com/watch?v=NlpS-DhayQA
---------------------------------------------------------------
Как обсуждали Эндрю и Лоуренс, методы, которые вы уже изучили, можно применять к сложным изображениям, и вы можете начать решать с их помощью реальные сценарии. Они обсудили, как его можно использовать, например, для обнаружения болезней с помощью растения маниоки, и вы можете посмотреть видео, демонстрирующее это здесь. После просмотра переходите к следующему уроку!

3(w4)-video2: Understanding ImageDataGenerator (15.MLg_1c)

To this point, you built an image classifier that worked using a deep neural network and you saw how to improve its performance by adding convolutions. One limitation though was that it used a dataset of very uniform images. Images of clothing that was staged and framed in 28 by 28. But what happens when you use larger images and where the feature might be in different locations? For example, how about these images of horses and humans? They have different sizes and different aspect ratios. The subject can be in different locations. In some cases, there may even be multiple subjects. In addition to that, the earlier examples with a fashion data used a built-in dataset. All of the data was handily split into training and test sets for you and labels were available. In many scenarios, that's not going to be the case and you'll have to do it for yourself. So in this lesson, we'll take a look at some of the APIs that are available to make that easier for you. In particular, the image generator in TensorFlow. One feature of the image generator is that you can point it at a directory and then the sub-directories of that will automatically generate labels for you. So for example, consider this directory structure. You have an images directory and in that, you have sub-directories for training and validation. When you put sub-directories in these for horses and humans and store the requisite images in there, the image generator can create a feeder for those images and auto label them for you. So for example, if I point an image generator at the training directory, the labels will be horses and humans and all of the images in each directory will be loaded and labeled accordingly. Similarly, if I point one at the validation directory, the same thing will happen. So let's take a look at this in code. The image generator class is available in Keras.preprocessing.image. You can then instantiate an image generator like this. I'm going to pass rescale to it to normalize the data. You can then call the flow from directory method on it to get it to load images from that directory and its sub-directories. It's a common mistake that people point the generator at the sub-directory. It will fail in that circumstance. You should always point it at the directory that contains sub-directories that contain your images. The names of the sub-directories will be the labels for your images that are contained within them. So make sure that the directory you're pointing to is the correct one. You put it in the second parameter like this. Now, images might come in all shapes and sizes and unfortunately for training a neural network, the input data all has to be the same size, so the images will need to be resized to make them consistent. The nice thing about this code is that the images are resized for you as they're loaded. So you don't need to preprocess thousands of images on your file system. But you could have done that if you wanted to. The advantage of doing it at runtime like this is that you can then experiment with different sizes without impacting your source data. While the horses and humans dataset is already in 300 by 300, when you use other datasets they may not always be uniformly sized. So this is really useful for you. The images will be loaded for training and validation in batches where it's more efficient than doing it one by one. Now, there's a whole science to calculating batch size that's beyond the scope of this course, but you can experiment with different sizes to see the impact on the performance by changing this parameter. Finally, there's the class mode. Now, this is a binary classifier i.e. it picks between two different things; horses and humans, so we specify that here. Other options in particular for more than two things will be explored later in the course. The validation generator should be exactly the same except of course it points at a different directory, the one containing the sub-directories containing the test images. When you go through the workbook shortly, you'll see how to download the images as a zip, and then sort them into training and test sub-directories, and then put horses and humans sub-directories in each. That's just pure Python. It's not TensorFlow or any other deep learning stuff. But it's all explained for you in the notebook.
---------------------------------------------------------------
До этого момента вы делали классификатор изображений, работавший на основе глубокой нейронной сети, и вы посмотрели, как улучшить его результаты, добавляя свёртки. Впрочем, одно ограничение было связано с тем, что применялся набор однородных изображений. Изображений одежды, которые были подготовлены и вписаны в рамки 28х28. Но что происходит, при использовании более крупных изображений, где признаки могут находиться в разных их частях? Например, как насчёт этих изображений лошадей и людей? У них разные размеры и разные пропорции. Объект может быть в разных местах. Иногда может даже присутствовать несколько объектов. В дополнение к этому, в более ранних примерах с одеждой использовался встроенный набор данных. Все данные были удобным образом разделены на обучающий и тестовый наборы, и были доступны метки. Во многих сценариях такого не будет, и вам придется делать это самостоятельно. На этом уроке мы посмотрим на некоторые из API, позволяющие упростить эту задачу. В частности, генератор изображений (ImageGenerator) в TensorFlow. Одной из функций генератора изображений является то, что вы можете указать ему директорию, и по структуре её поддиректорий за вас автоматически будут сгенерированы метки. Например, рассмотрим вот эту структуру. У нас есть директория Images (изображения), в которой есть поддиректории Training(обучение) и Validation(проверка). Когда вы в них создаёте поддиректории для лошадей и людей и сохраняете в них необходимые изображения, то генератор изображений может создать раздатчик для этих изображений и автоматически их вам разметить. Так, например, если я укажу генератору изображений директорию для обучения, то метками будут "лошади" и "люди", а все изображения из каждой поддиректории будут загружены и размечены соответственно. Аналогичным образом, если я укажу директорию Validation, то произойдёт то же самое. Давайте посмотрим на это в коде. Класс ImageGenerator находится в keras.preprocessing.image. И далее вот таким образом можно создать экземпляр ImageGenerator. Я передам параметр rescale, чтобы нормализовать данные. Затем мы вызываем метод flow_from_directory, чтобы он загрузил изображения из этой директории и её поддиректорий. Распространённой ошибкой является то, что люди указывают генератору поддиректорию. В этом случае произойдёт ошибка. Вы всегда должны указывать директорию, содержащую поддиректории, в которых лежат изображения. Имена поддиректорий станут метками для содержащихся в них изображений. Поэтому убедитесь, что вы указали правильную директорию. Вы передаёте её как входной параметр вот здесь. Изображения могут быть любой формы и размера, но к сожалению, для обучения нейронной сети все входные данные должны быть одного размера. Поэтому изображения нужно отмасштабировать, чтобы привести к единому размеру. И в этом коде хорошо то, что изображения масштабируются во время загрузки. Поэтому вам не прийдётся предобрабатывать тысячи изображений в вашей файловой системе. Но вы могли бы это сделать, при желании. Преимущество подхода, когда вы делаете это в процессе исполнения, как здесь, — является то, что вы можете экспериментировать с различными размерами без изменения исходных данных. Хотя набор данных с лошадьми и людьми сам по себе размером 300х300, но если вы будете использовать другие наборы, их содержимое не всегда будет одного размера. Поэтому это будет вам очень полезно. Изображения для обучения и проверки будут загружаться пакетами, когда это эффективнее, чем загружать их по одному. Это целая наука — как посчитать размер пакета, и это выходит за рамки этого курса, но вы можете экспериментировать с различными размерами, меняя этот параметр, чтобы посмотреть, как это повлияет на результативность. Последний параметр — это class_mode. Здесь мы используем двоичный классификатор, т.е., он выбирает между двумя различными вещами: лошадьми и людьми — поэтому мы его здесь и указали. Другие варианты, в частности, когда классов больше двух, — будут рассмотрены далее в этом курсе. Проверочный генератор (validation_generator) должен быть точно таким же, за исключением, конечно, того, что он указывает на другую директорию. На ту, которая содержит поддиректории, содержащие тестовые изображения. Если вы бегло пройдёте по рабочей тетради, то увидите, как скачать изображения в виде zip-архива, рассортировать их по поддиректориям для обучения и для тестов, а затем поместить поддиректории с лошадьми и людьми в каждую из них. Это всё чистый Python. Это не TensorFlow или что-то ещё, касающееся глубокого обучения. Но это всё поясняется в тетради.

4(w4)-Designing the neural network: (15.MLg_1c)

(Проектирование нейронной сети)
Now that you’ve seen how an ImageDataGenerator can flow images from a directory and perform operations such as resizing them on the fly, the next thing to do is design the neural network to handle these more complex images. You’ll see that in the next video.
---------------------------------------------------------------
Теперь, когда вы увидели, как ImageDataGenerator может передавать изображения из каталога и выполнять такие операции, как изменение их размера на лету, следующее, что нужно сделать, — это спроектировать нейронную сеть для обработки этих более сложных изображений. Вы увидите это в следующем видео.

5(w4)-video3: Defining a ConvNet to use complex images (15.MLg_1c)

(Определение ConvNet для использования сложных изображений)
So let's now take a look at the definition of the neural network that we'll use to classify horses versus humans. It's very similar to what you just used for the fashion items, but there are a few minor differences based on this data, and the fact that we're using generators. So here's the code. As you can see, it's the sequential as before with convolutions and pooling before we get to the dense layers at the bottom. But let's highlight some of the differences. First of all, you'll notice that there are three sets of convolution pooling layers at the top. This reflects the higher complexity and size of the images. Remember our earlier our 28 by 28.5 to 13 and then five before flattening, well, now we have 300 by 300. So we start at 298 by 298 and then have that etc., etc. until by the end, we're at a 35 by 35 image. We can even add another couple of layers to this if we wanted to get to the same ballpark size as previously, but we'll keep it at three for now. Another thing to pay attention to is the input shape. We resize their images to be 300 by 300 as they were loaded, but they're also color images. So there are three bytes per pixel. One byte for the red, one for green, and one for the blue channel, and that's a common 24-bit color pattern. If you're paying really close attention, you can see that the output layer has also changed. Remember before when you created the output layer, you had one neuron per class, but now there's only one neuron for two classes. That's because we're using a different activation function where sigmoid is great for binary classification, where one class will tend towards zero and the other class tending towards one. You could use two neurons here if you want, and the same softmax function as before, but for binary this is a bit more efficient. If you want you can experiment with the workbook and give it a try yourself. Now, if we take a look at our model summary, we can see the journey of the image data through the convolutions The 300 by 300 becomes 298 by 298 after the three by three filter, it gets pulled to 149 by 149 which in turn gets reduced to 73 by 73 after the filter that then gets pulled to 35 by 35, this will then get flattened, so 64 convolutions that are 35 squared and shape will get fed into the DNN. If you multiply 35 by 35 by 64, you get 78,400, and that's the shape of the data once it comes out of the convolutions. If we had just fed raw 300 by 300 images without the convolutions, that would be over 90,000 values. So we've already reduced it quite a bit.
---------------------------------------------------------------
Давайте сейчас посмотрим на определение нейронной сети, которую мы будем использовать для различения лошадей от людей. Она очень похожа на ту, что вы недавно использовали для предметов одежды, но есть несколько незначительных отличий, связанных с данными, и с тем, что мы используем генераторы. Вот он, код. Как вы можете видеть — это, как и раньше, последовательная модель со свёрточными слоями и пулингом, после которых уже мы добираемся до полносвязных слоёв внизу. Но давайте остановимся на некоторых различиях. Во-первых, можно видеть, что здесь сверху три набора слоёв "свёртка + пулинг". Это отражает более высокую сложность и размер изображений. Помните, ранее наши картинки 28х28 перед развертыванием сокращались сперва вдвое — до 13, а затем до 5. Сейчас же у нас изображения 300х300. Поэтому мы начинаем с 298х298, а затем сокращаем его вдвое снова и снова, пока в конце концов не дойдём до изображения 35х35. Можно было бы добавить и еще пару слоёв, если бы мы хотели достичь примерно того же размера, что и раньше, но пока оставим три. Еще одна вещь, на которую стоит обратить внимание, — это размерность входных данных. Мы масштабируем изображения к размеру 300х300 при их загрузке, но они, к тому же, являются цветными изображениями. Поэтому в них хранится по 3 байта на пиксел. Один байт для красного, один для зелёного, и один для синего канала, это типовая 24-битная цветовая палитра. И если как следует присмотреться, то вы увидите, что выходной слой также изменился. Вспомните, раньше при создании выходного слоя у вас был один нейрон на каждый класс, но теперь у нас только один нейрон для двух классов. Это потому, что мы сейчас используем другую функцию активации, и сигмоида отлично подходит для бинарной классификации. С ней один класс будет стремиться к 0, а другой класс будет стремиться к 1. Вы бы могли здесь, при желании, использовать 2 нейрона и ту же softmax функцию, что и прежде, но для двоичного случая нынешний вариант чуть эффективнее. Если вы хотите, то можете поэкспериментировать с рабочей тетрадью и проверить это самостоятельно. Если мы теперь посмотрим на сводку по нашей модели, то увидим весь путь, который проходит изображение через свёртки. Картинка 300х300 становится 298х298 после прохождения фильтра 3х3, далее оно сжимается до 149х149, что, в свою очередь, сокращается до 73х73 после фильтра, и затем происходит сжатие до 35х35. Затем это всё разворачивается, то есть, разворачиваются 64 свёртки 35х35, и результат идёт на вход полносвязной нейронной сети. Если вы перемножите 35 * 35 * 64, то получите 78,400, и это та размерность данных, которые получаются на выходе свёрток. Если бы мы просто скармливали оригинальные изображения 300х300 без свёрток, то это было бы более 900,000 значений. Так что мы уже ощутимо сократили их число.

6(w4)-Train the ConvNet with ImageDataGenerator: (15.MLg_1c)

(Train the ConvNet with ImageDataGenerator)
Now that you’ve designed the neural network to classify Horses or Humans, the next step is to train it from data that’s on the file system, which can be read by generators. You'll see how to do this in the next video.
---------------------------------------------------------------
Теперь, когда вы разработали нейронную сеть для классификации лошадей или людей, следующим шагом будет ее обучение на основе данных, находящихся в файловой системе, которые могут быть прочитаны генераторами. Как это сделать, вы увидите в следующем видео.

7(w4)-video4: Training the ConvNet (15.MLg_1c)

Okay, we'll now compile the model and, as always, we have a loss function and an optimizer. When classifying the ten items of fashion, you might remember that your loss function was a categorical cross entropy. But because we're doing a binary choice here, let's pick a binary_crossentropy instead. Also, earlier we used an Adam optimizer. Now, you could do that again, but I thought it would be fun to use the RMSprop, where you can adjust the learning rate to experiment with performance. To understand learning rate and how all that fits together, check out this great video from deeplearning.ai that goes into it in a lot more detail.
For now, I'm not going to go into the details in this course. Okay, next up is the training, now, this looks a little different than before when you called model.fit. And that's because we're using a generator instead of datasets. Remember the image generator from earlier, let's look at each parameter in detail. The first parameter is the training generator that you set up earlier. This streams the images from the training directory. Remember the batch size you used when you created it? That's important in the next step. There are 1,024 images in the training directory, so we're loading them in 128 at a time. So in order to load them all, we need to do 8 batches. So we set the steps_per_epoch to cover that.
Here we just set the number of epochs to train for. This is a bit more complex, so let's use, say, 15 epochs in this case. And now we specify the validation set that comes from the validation_generator that we also created earlier. It had 256 images, and we wanted to handle them in batches of 32, so we will do 8 steps.
And the verbose parameter specifies how much to display while training is going on. With verbose set to 2, we'll get a little less animation hiding the epoch progress. Once the model is trained, you will, of course, want to do some prediction on the model. And here's the code to do that, let's look at it piece by piece.
So these parts are specific to Colab, they are what gives you the button that you can press to pick one or more images to upload. The image paths then get loaded into this list called uploaded. The loop then iterates through all of the images in that collection. And you can load an image and prepare it to input into the model with this code. Take note to ensure that the dimensions match the input dimensions that you specified when designing the model. You can then call model.predict, passing it the details, and it will return an array of classes. In the case of binary classification, this will only contain one item with a value close to 0 for one class and close to 1 for the other.
Later in this course you'll see multi-class classification with Softmax. Where you'll get a list of values with one value for the probability of each class and all of the probabilities adding up to 1
---------------------------------------------------------------
Теперь скомпилируем модель, и как обычно, у нас есть функция потерь и оптимизатор. Как вы, наверное, помните, при классификации десяти предметов одежды функцией потерь — была categorical_crossentropy. Но т.к. здесь мы делаем бинарный выбор, то давайте возьмём binary_crossentropy. Также ранее мы использовали оптимизатор Adam. Сейчас вы могли бы сделать это снова, но я подумал, что было бы любопытно использовать RMSprop, где вы можете настроить скорость обучения, чтобы поэкспериментировать с качеством. Чтобы понять, что такое скорость обучения, и как всё это связано — посмотрите отличное видео от deeplearning.ai (https://youtu.be/zLRB4oupj6g), в котором это объясняется куда подробнее.
А пока я не буду вдаваться в такие детали в этом курсе. Хорошо, следующий шаг — это обучение. Оно выглядит немного иначе, чем раньше, когда вы вызывали model.fit(). Потому что теперь вы вызываете model.fit_generator(), поскольку мы используем генератор вместо наборов данных. Вспомните генератор изображений, который у нас был, и рассмотрим каждый параметр вызова подробнее. Первый параметр — это train_generator, который вы настраивали ранее. Он выдаёт поток изображений из директории для обучения. Помните, при его создании мы задавали размер пакетов, он был равен 128. [оговорка в оригинале - прим.] Это важно для следующего шага. В директории для обучения находится 1024 изображения, и мы загружаем их по 128 штук за раз. Поэтому для того, чтобы загрузить их все, нам нужно сделать 8 пакетов. Соответственно, мы установили steps_per_epoch=8, чтобы это обеспечить.
Здесь (epochs=15) мы просто указываем количество эпох для обучения. Эта тема несколько сложнее, поэтому давайте использовать здесь, скажем, 15 эпох. А сейчас мы указываем набор данных для валидации, который нам даст validation_generator, также созданный ранее. Он содержит 256 изображений, и мы хотели обрабатывать их пакетами по 32 штуки. Так что мы будем делать по 8 шагов.
А параметр verbose определяет, сколько информации отображать во время обучения. При verbose=2 мы получим немного меньше анимации, скрывая продвижение по эпохам. Как только модель обучена, вы, конечно же, захотите сделать несколько предсказаний с её помощью. И вот он код, чтобы это сделать. Давайте разберём его по частям.
Вот эти части специфичны для Colab, это даст нам кнопку, которую можно нажать для загрузки следующей порции изображений. Пути к изображениям будут загружены в этот список с названием uploaded. Далее следует цикл, проходящий по всем изображениям в этой коллекции. Данный код позволит вам загрузить изображение и подготовить его для передачи в модель. Проверьте, чтобы его размерность совпадала с размерностью входа, которую вы определили при проектировании модели. Затем можно вызвать model.predict, передавая в неё детали, — и она вернёт массив классов. В случае бинарной классификации, он будет содержать лишь один элемент со значением, близким к 0 для первого класса, и близким к 1 для второго.
Далее в этом курсе вы увидите мультиклассовую классификацию, использующую Softmax, где на выходе будет список значений, каждое из которых соответствует вероятности своего класса, и сумма всех вероятностей равна 1.

8(w4)-Exploring the solution: (15.MLg_1c)

(Изучение решения)
Now you’ve gone through the code to define the neural network, train it with on-disk images, and then predict values for new images. Let’s see this in action in a workbook. In the next video, Laurence will step you through the code, and afterward, you can try it for yourself.
---------------------------------------------------------------
Теперь вы прошли через код, чтобы определить нейронную сеть, обучить ее изображениям на диске, а затем предсказать значения для новых изображений. Давайте посмотрим на это в действии в рабочей тетради. В следующем видео Лоуренс покажет вам код, после чего вы сможете попробовать его сами.

9(w4)-video5: Walking through developing a ConvNet (15.MLg_1c)

(Прохождение разработки ConvNet)
Okay. So you've just seen how to get started with creating a neural network in Keras that uses the image generator to automatically load and label your files based on their subdirectories. Now, let's see how we can use that to build a horses or humans classifier with a convolutional neural network. This is the first notebook you can try. To start, you'll download the zip file containing the horses and humans data. Once that's done, you can unzip it to the temp directory on this virtual machine. The zip file contain two folders; one called filtered horses, and one called filtered humans. When it was unzipped, these were created for you. So we'll just point a couple of variables at them, and then we can explore the files by printing out some of the filenames. Now, these could be used to generate labels, but we won't need that if we use the Keras generator. If you wanted to use this data without one, a filenames will have the labels in them of course though. We'll print out the number of images that we have to work with, and there's a little over 1000 of them, and now we can display a few random images from the dataset. Here, we can see eight horses and eight humans. An interesting aspect of this dataset is that all of the images are computer-generated. I've rendered them to be as photo-real as possible, but there'll be actually used to classify real pictures of horses and people, and here's a few more images just to show some of the diversity. Let's start building the model. First, we'll import TensorFlow, and now we'll build the layers. We have quite a few convolutions here because our source images are quite large, are 300 by 300. Later we can explore the impact of reducing their size and needing less convolutions. We can print the summary of the layers, and here we can see by the time we reach the dense network, the convolutions are down to seven-by-seven. Okay. Next up, we'll compile our network. It's using binary cross entropy as the loss, binary because we're using just two classes, and the optimizer is an RMSprop that allows us to tweak the learning rate. Don't worry if you don't fully understand these yet, there are links out to content about them where you can learn more.
---------------------------------------------------------------
Вы только что увидели, как начать создавать в Keras нейронную сеть, использующую генератор изображений для автоматической загрузки и разметки ваших файлов на основе поддиректорий, где они лежат. А сейчас давайте посмотрим, как можно это использовать при построении классификатора лошадей и людей с помощью свёрточной нейронной сети. Это первый блокнот для ваших экспериментов. Чтобы начать, вы должны загрузить zip-файл, содержащий данные с лошадьми и людьми. Как только это будет сделано, вы можете распаковать его во временный каталог на этой виртуальной машине. Zip-файл содержит две папки: одна называется filtered_horses, а другая называется filtered_humans. Они будут созданы в результате распаковки архива. Поэтому мы просто создадим пару переменных, ссылающихся на них, и тогда можно изучить их содержимое, выведя имена некоторых файлов на экран. Можно использовать их для создания меток, но нам это не нужно, если мы используем генератор Keras. Если вы хотите использовать эти данные без него, то имена файлов, разумеется, будут содержать в своём составе метки. Мы выведем количество изображений, с которыми прийдётся работать. Их немногим более 1000, и теперь мы можем отобразить несколько случайно выбранных изображений из набора данных. Вы видите здесь восемь лошадей и восемь людей. Любопытная черта этого набора данных — в том, что все изображения были сгенерированы компьютером. Я отрендерил их так, чтобы они были максимально фотореалистичны, поскольку на самом деле они будут использованы для классификации реальных фотографий лошадей и людей. И вот ещё несколько изображений, чтобы просто показать их разнообразие. Давайте начнём строить модель. Сначала импортируем TensorFlow, а здесь построим слои. У нас здесь немало свёрток, поскольку исходные изображения достаточно большие, размером 300х300. Позже мы рассмотрим, как повлияет уменьшение их размера и потребность в меньшем числе свёрток. Мы можем вывести сводную информацию о слоях, и здесь видно, что к моменту достижения полносвязной сети свёртки уменьшатся до размера 7х7. Следующим шагом мы скомпилируем сеть. Здесь используется binary_crossentropy в качестве функции потерь. Бинарная, т.к. мы используем только 2 класса. А в качестве оптимизатора выбран RMSprop, который позволяет нам настроить темп обучения. Не волнуйтесь, если вы пока не до конца всё это понимаете. Перейдя по указанным ссылкам, вы можете узнать об этом больше.

10(w4)-Training the neural network: (15.MLg_1c)

Now that you’ve learned how to download and process the horses and humans dataset, you’re ready to train. When you defined the model, you saw that you were using a new loss function called ‘Binary Crossentropy’,
https://gombru.github.io/2018/05/23/cross_entropy_loss/
, and a new optimizer
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
called RMSProp.
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/experimental/RMSprop
f you want to learn more about the type of binary classification we are doing here, check out this
https://www.youtube.com/watch?v=eqEc66RFY0I&t=6s
great video from Andrew!
---------------------------------------------------------------
Теперь, когда вы научились загружать и обрабатывать набор данных о лошадях и людях, вы готовы к обучению. Когда вы определили модель, вы увидели, что используете новую функцию потерь под названием «Бинарная кроссэнтропия».
https://gombru.github.io/2018/05/23/cross_entropy_loss/
, и новый оптимизатор
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
называется RMSProp.
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/experimental/RMSprop
Если вы хотите узнать больше о типе бинарной классификации, которую мы здесь делаем, ознакомьтесь с этим
https://www.youtube.com/watch?v=eqEc66RFY0I&t=6s
отличное видео от Андрея!

11(w4)-video6: Walking through training the ConvNet (15.MLg_1c)

Next up is where we use the ImageDataGenerator. We instantiate it and we scale our images to 1 over 255, which then normalizes their values. We then point it at the main directory where we see the unzipped files.
We can see that it finds all of the images, and has assigned them to two classes, because they were two sub directories.
We'll now train the neural network for 15 epochs, it will take about two minutes.
Each epoch is loading the data, calculating the convolutions and then trying to match the convolutions to labels. As you can see, the accuracy mostly increases but it will occasionally dip, showing the gradient ascent of the learning actually in action.
It's always a good idea to keep an eye on fluctuations in this figure. And if there are too wild, you can adjust the learning rate.
Remember the parameter to RMS prop when you compile the model, that's where you'd tweak it. It's also going pretty fast, because right here, I'm training on a GPU machine.
By the time we get to epoch 15, we can see that our accuracy is about 0.9981, which is really good. But remember, that's only based on the data that the network has already seen during training, which is only about 1,000 images. So don't get lulled into a false sense of security.
Let's have a bit of fun with the model now and see if we can predict the class for new images that it hasn't previously seen.
Let's go to Pixelbay, and see what we can find. I'll search for horses, and there's lots of horses, so let's pick this one. It's a white horse running in the snow. I'm going to download it to my file system. I'm now going to go back to the notebook, and I'm going to upload the image from my file system. And we'll see that it gets uploaded, and it's classified as a horse. So let's try another one. Like this one here. Which I'll then upload to the notebook, and we'll see that it's also classified as a horse.
I'll now go back to Pixelbay and search for person, and pick this image of a girl sitting on a bench. I'll download it to my file system, upload it to the neural network, and we can see that this is also correctly classified as a human.
Let's do one more. I'll go back to the list of results on Pixelbay, and pick this image of a girl. As before, I'll download it to my file system and I'll upload it to the neural network and we'll also see that it's still detects a human in the image.
Now one other thing that I can do with this script is upload multiple files and have it classify all of them at once. And here we can see all of the classifications. We have four out four correct.
This notebook also includes some visualizations of the image as it passes through the convolutions. You can give it a try with this script.
Here you can see where a human image was convolved and features such as the legs really lit up. And if I run it again, we can see another human with similar features. Also the hair is very distinctive. Have a play with it for yourself and see what you discover.
So there, we saw a convolutional neural network create a classifier to horses or humans using a set of about 1,000 images. The four images we tested all worked, but that's not really scalable. And the next video, we'll see how we can add a validation set to the training and have it automatically measure the accuracy of the validation set, too.
---------------------------------------------------------------
Следующим шагом будет использование ImageDataGenerator. Мы создаём экземпляр этого класса и умножаем значения пикселов на 1/255, что нормализует их значения. Затем мы задаём ему основную директорию, где находятся распакованные файлы.
Мы видим, что генератор нашёл все изображения, и отнёс их двум классам, ведь они находились в двух поддиректориях. А сейчас мы обучим нейронную сеть за 15 эпох, что займёт около двух минут.
В каждой эпохе загружаются данные, просчитываются свёртки, а затем выполняется попытка сопоставить свёртки их меткам. Как вы видите, точность в большинстве случаев увеличивается, но иногда и проседает вниз, отражая работу градиентного спуска при обучении.
Будет полезно всегда следить за его колебаниями, и если они слишком резкие, то можно отрегулировать темп обучения.
Помните параметр RMSprop, заданный при компиляции модели? Вот где вы можете подстроить темп. Обучение проходит довольно быстро, поскольку сейчас я обучаю сеть на машине с GPU.
Между тем, мы дошли до 15 эпохи, и видим, что наша точность в районе 0.9981, что очень здорово. Но помните, что это лишь на тех данных, которые сеть уже видела во время обучения, где всего около 1,000 изображений. Поэтому не полагайтесь на ложное чувство уверенности.
Давайте теперь немного поиграемся с моделью, и посмотрим, сможем ли мы предугадать класс для новых изображений, которые сеть не видела ранее.
Давайте зайдём на Pixabay и посмотрим, что там можно найти. Я поищу лошадей, и здесь куча лошадей. Давайте возьмём вот эту. Это белая лошадь, бегущая по снегу. Я скачаю её к себе на диск. Теперь возвращаемся назад к блокноту, и загрузим изображение с моей файловой системы. И мы видим, что оно загрузилось, и было классифицировано как лошадь. Давайте попробуем другое изображение. Вот это, например. Которое я загружаю в блокнот, и мы видим, что оно также было классифицировано как лошадь.
Теперь я возвращаюсь на Pixabay и поищу человека. Возьмём это изображение девочки, сидящей на скамье. Загружаем его в файловую систему, далее загрузим его в нейронную сеть, и мы увидим, что оно было также корректно классифицировано как человек.
Давайте возьмём ещё одно. Я возвращаюсь к результатам поиска на Pixabay и возьму вот это изображение девочки. Как и раньше, я скачаю его, а затем загружу его в нейронную сеть — и мы снова видим, что сеть по-прежнему находит человека на изображении.
Ещё я в этом скрипте могу сделать вот что: загрузить разом несколько файлов и классифицировать их все. Здесь мы видим все результаты классификации. Четыре из четырёх классифицированы верно.
Этот блокнот также содержит некоторую визуализацию того, как изображение проходит через свёртки. Вы можете попробовать её с помощью этого скрипта.
Мы здесь можем увидеть, как изображение человека было свёрнуто, и такие признаки, как ноги, действительно проявились. И если я выполню его снова, то мы увидим другого человека с похожими признаками. Волосы также являются сильной отличительной чертой. Поиграйтесь с этим самостоятельно и посмотрите, что вы обнаружите.
Итак, здесь мы увидели как с помощью свёрточной нейронной сети создать классификатор лошадей и людей, используя набор из порядка 1,000 изображений. Все 4 изображения, на которых мы его протестировали — работали, но всё это не очень масштабируемо. И в следующем видео мы увидим, как можно добавить проверочный набор к обучению, чтобы автоматически измерять точность также и на проверочном наборе данных.

12(w4)-Experiment with the horse or human classifier (Lab 1): (15.MLg_1c)

Now it’s your turn. You can find the notebook here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W4/ungraded_labs/C1_W4_Lab_1_image_generator_no_validation.ipynb
Work through it and get a feel for how the ImageGenerator is pulling the images from the file system and feeding them into the neural network for training. Have some fun with the visualization code at the bottom!
In earlier notebooks, you tweaked parameters like epochs, or the number of hidden layers and neurons in them. Give that a try for yourself, and see what the impact is. Spend some time on this.
Once you’re done, move to the next video, where you can validate your training against a lot of images!
---------------------------------------------------------------
Теперь твоя очередь. Блокнот можно найти здесь.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W4/ungraded_labs/C1_W4_Lab_1_image_generator_no_validation.ipynb
Поработайте над этим и почувствуйте, как ImageGenerator извлекает изображения из файловой системы и передает их в нейронную сеть для обучения. Повеселитесь с кодом визуализации внизу!
В более ранних записных книжках вы настраивали такие параметры, как эпохи или количество скрытых слоев и нейронов в них. Попробуйте сами и посмотрите, каков будет эффект. Потратьте на это некоторое время.
Как только вы закончите, переходите к следующему видео, где вы можете проверить свою тренировку на множестве изображений!

13(w4)-video7: Adding automatic validation to test accuracy (15.MLg_1c)

(Добавление автоматической проверки точности теста)
In the previous video, you saw how to build a convolutional neural network that classified horses against humans. When you are done, you then did a few tests using images that you downloaded from the web. In this video, you'll see how you can build validation into the training loop by specifying a set of validation images, and then have TensorFlow do the heavy lifting of measuring its effectiveness with that same. As before we download the dataset, but now will also download the separate validation dataset. We'll unzip into two separate folders, one for training, one for validation. We'll create some variables that pointed our training and validation subdirectories, and we can check out the filenames. Remember that the filenames may not always be reliable for labels. For example, here the validation horse labels aren't named as such while the human ones are. We can also do a quick check on whether we got all the data, and it looks good so we think we can proceed. We can display some of the training images as we did before, and let's just go straight to our model. Here we can import TensorFlow, and here we define the layers in our model. It's exactly the same as last time. We'll then print the summary of our model, and you can see that it hasn't changed either. Then we'll compile the model with the same parameters as before. Now, here's where we can make some changes. As well as an image generator for the training data, we now create a second one for the validation data. It's pretty much the same flow. We create a validation generator as an instance of image generator, re-scale it to normalize, and then pointed at the validation directory. When we run it, we see that it picks up the images and the classes from that directory. So now let's train the network. Note the extra parameters to let it know about the validation data. Now, at the end of every epoch as well as reporting the loss and accuracy on the training, it also checks the validation set to give us loss in accuracy there. As the epochs progress, you should see them steadily increasing with the validation accuracy being slightly less than the training. It should just take about another two minutes. Okay. Now that we've reached epoch 15, we can see that our accuracy is about 97 percent on the training data, and about 85 percent on the validation set, and this is as expected. The validation set is data that the neural network hasn't previously seen, so you would expect it to perform a little worse on it. But let's try some more images starting with this white horse.
We can see that it was misclassified as a human. Okay, let's try this really cute one.
We can see that's correctly classified as a horse. Okay, let's try some people.
Let's try this woman in a blue dress. This is really interesting picture because she has her back turned, and her legs are obscured by the dress, but she's correctly classified as a human. Okay, here's a tricky one. To our eyes she's human, but will the wings confuse the neural network?
And they do, she is mistaken for a horse. It's understandable though particularly as the training set has a lot of white horses against the grassy background.
How about this one? It has both a horse and the human in it, but it gets classified as a horse. We can see the dominant features in the image are the horse, so it's not really surprising. Also there are many white horses in the training set, so it might be matching on them. Okay one last one. I couldn't resist this image as it's so adorable, and thankfully it's classified as a horse. So, now we saw the training with a validation set, and we could get a good estimate for the accuracy of the classifier by looking at the results with a validation set. Using these results and understanding where and why some inferences fail, can help you understand how to modify your training data to prevent errors like that. But let's switch gears in the next video. We'll take a look at the impact of compacting your data to make training quicker.
---------------------------------------------------------------
В предыдущем видео вы увидели, как построить свёрточную нейронную сеть, которая отличала лошадей от людей. После того, как вы это сделали, вы выполнили несколько тестов, используя изображения, которые скачали из интернета. В этом видео вы увидите, как можно встроить проверку в цикл обучения, указав набор проверочных изображений. И тогда TensorFlow сделает всю грязную работу по измерению эффективности с этим набором. Как и раньше, мы скачаем набор данных. Но на этот раз мы также скачаем отдельно и проверочный набор. Мы распакуем их в две отдельные папки: одну для обучения и одну для проверки. Мы создадим несколько переменных, указывающих на наши поддиректории для обучения и для проверки, и мы можем проверить названия файлов. Помните, что названия файлов не всегда могут надёжно отражать метки. Например, здесь метки лошадей в проверочном наборе не соответствуют названиям, хотя для меток людей это так. Мы также можем выполнить быструю проверку того, все ли данные мы получили. Вроде бы всё хорошо, поэтому, думаю, мы можем продолжать. Мы можем отобразить некоторые из учебных изображений, как мы это делали раньше. И давайте перейдём прямо к нашей модели. Здесь мы можем импортировать TensorFlow, а здесь мы определяем слои нашей модели. Всё точно так же, как в прошлый раз. Затем мы выведем информацию по нашей модели, и вы видите, что она вообще не изменилась. Далее скомпилируем модель с теми же параметрами, как и раньше. А вот здесь мы можем сделать кое-какие изменения. В дополнение к генератору изображений для обучающих данных, мы создадим второй такой же, но для проверочных данных. Это по сути все те же действия. Мы создаём validation_generator как экземпляр ImageGenerator, изменяем масштаб значений для нормализации и указываем ему путь к проверочной директории. Когда мы запустим его, то увидим, что он подхватил изображения и классы из этой директории. А теперь давайте обучим сеть. Обратите внимание на дополнительные параметры, указывающие модели на проверочные данные. Теперь в конце каждой эпохи, помимо вывода потерь и точности обучения, производится проверка на проверочных данных, чтобы выдать нам соответствующие потери и точность. По мере прохождения эпох вы должны видеть, что они постоянно растут, а точность на проверочных данных немного меньше, чем на обучающих. Это должно занять ещё две минуты. Готово. Теперь, когда мы достигли 15 эпохи, мы видим, что наша точность около 97% на обучающих данных и около 85% на проверочных данных. И это то, что и ожидалось. Проверочный набор — это данные, которые нейронная сеть раньше не видела, поэтому было ожидаемо, что она будет работать с ними немного хуже. Но давайте попробуем ещё несколько изображений. Начнём с этой белой лошади.
И мы видим, что она была ошибочно классифицирована как человек. Хорошо, давайте попробуем вот эту симпатичную лошадь.
Мы видим, что она была правильно классифицирована как лошадь. Так, а теперь давайте попробуем несколько людей.
Давайте попробуем вот эту женщину в синем платье. Это действительно интересная картинка, т.к. она повёрнута спиной, а её ноги скрыты за платьем, но она всё же правильно классифицирована как человек. А теперь картинка посложнее. Мы видим здесь человека, но собьют ли с толку 'крылья' нейронную сеть?
Да, сбили — она ошибочно решила, что здесь лошадь. Это можно понять, особенно когда обучающий набор содержит кучу белых лошадей на фоне травы.
Как насчёт вот этого изображения? На нём есть оба: и лошадь и человек,
Но оно было классифицировано как лошадь. Мы видим, что преобладающие признаки на изображении относятся к лошади, поэтому это не так уж и неожиданно. Также в обучающем наборе много белых лошадей, и, возможно, изображение похоже на них. Так, последнее. Я не смог пропустить это изображение, так как оно очаровательно, и, к счастью, оно было классифицировано как лошадь. Мы только что увидели обучение с проверочным набором, и мы смогли получить хорошую оценку для точности классификатора, глядя на результаты на проверочном наборе. Использование этих результатов и понимание, где и почему некоторые выводы были ложными, может помочь вам понять, как изменить ваши обучающие данные, чтобы предотвратить подобные ошибки. Но давайте в следующем видео перейдём на следующую скорость. Мы посмотрим как сжатие данных влияет на возможность ускорить обучение.

14(w4)-Get hands-on and use validation (Lab 2): (15.MLg_1c)

(Получите практический опыт и используйте проверку (лабораторная работа 2))
Now you can give it a try for yourself. Here is the notebook that Laurence went through in the video. Have a play with it to see how it trains, and test some images yourself! Once you’re done, move on to the next video where you’ll compact your data to see the impact on training.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C1/W4/ungraded_labs/C1_W4_Lab_2_image_generator_with_validation.ipynb
---------------------------------------------------------------
Теперь вы можете попробовать сами. Вот блокнот, который Лоуренс просматривал в видео. Поиграйте с ним, чтобы увидеть, как он тренируется, и протестируйте некоторые изображения сами! Как только вы закончите, перейдите к следующему видео, где вы будете сжимать свои данные, чтобы увидеть влияние на обучение.

15(w4)-video8: Exploring the impact of compressing images (15.MLg_1c)

(Изучение влияния сжатия изображений)
The images in the horses are humans dataset are all 300 by 300 pixels. So we had quite a few convolutional layers to reduce the images down to condensed features. Now, this of course can slow down the training. So let's take a look at what would happen if we change it to a 150 by a 150 for the images to have a quarter of the overall data and to see what the impact would be. We'll start as before by downloading and unzipping the training and test sets.
Then we'll point some variables in the training and test sets before setting up the model. First, we'll import TensorFlow and now we'll define the layers for the model. Note that we've changed the input shape to be 150 by 150, and we've removed the fourth and fifth convolutional max pool combinations. Our model summary now shows the layer starting with the 148 by 148, that was the result of convolving the 150 by 150. We'll see that at the end, we end up with a 17 by 17 by the time we're through all of the convolutions and pooling. We'll compile our model as before, and we'll create our generators as before, but note that the target size has now changed to 150 by 150.
Now we can begin the training, and we can see that after the first epoch that the training is fast, and accuracy and validation aren't too bad either. The training continues and both accuracy values will tick up.
Often, you'll see accuracy values that are really high like 1.000, which is likely a sign that you're overfitting. We reach the end, I have really high accuracy on the test data, about 0.99, which is much too high. The validation set is about 0.84, which is pretty good, but let's put it to the test with some real images.
Let's start with this image of the girl and the horse. It still classifies as a horse. Next, let's take a look at this cool horsey,and who's still correctly categorized.
These cuties are also correctly categorized, but this one is still wrongly categorized. But the most interesting I think is this woman. When we use 300 by 300 before and more convolutions, she was correctly classified. But now, she isn't. This is a great example of the importance of measuring your training data against a large validation set, inspecting where it got it wrong and seeing what you can do to fix it. Using this smaller set is much cheaper to train, but then errors like this woman with her back turned and her legs obscured by the dress will happen, because we don't have that data in the training set. That's a nice hint about how to edit your dataset for the best effect in training.
---------------------------------------------------------------
Все изображения в наборе данных с лошадьми и людьми имеют размер 300х300 пикселов. Поэтому у нас было немало свёрточных слоёв для уменьшения изображений до уплотнённых признаков. Разумеется, это может замедлить обучение. Давайте посмотрим, что произойдёт, если мы изменим размер изображений на 150х150, оставив четверть от всех данных, — увидим, каким будет эффект. Начнем, как и раньше, с загрузки и распаковки обучающего и тестового наборов.
Затем перед созданием модели определим несколько переменных, ссылающихся на обучающий и тестовый наборы. Сначала импортируем TensorFlow, а затем определим слои в модели. Обратите внимание, что мы изменили размерность входных данных на 150х150, и удалили четвёртую и пятую комбинации свёрточного и MaxPooling слоёв. Информация по нашей модели теперь показывает слои, начиная со 148х148, что является результатом свёртки 150х150. И мы видим, что в конце мы приходим к 17х17, когда пройдём все свёртки и сжатие. Скомпилируем нашу модель, как и раньше. И мы создаём наши генераторы так же, как и ранее, но обратите внимание, что целевой размер теперь изменён до 150х150.
Сейчас мы можем начать обучение, и мы видим, что после первой эпохи обучение становится быстрым, при этом точность и валидация тоже не так уж и плохи. Обучение продолжается, и оба значения точности растут.
Зачастую вы будете видеть действительно высокие значения точности — в районе 1.000, что, скорее всего, является симптомом переобучения. Мы достигли конца с очень высокой точностью на тренировочных данных, около 0.99, что слишком много. На проверочном наборе точность в районе 0.84, что довольно хорошо, но давайте теперь протестируем на нескольких реальных изображениях.
Давайте начнём с этого изображения девушки и лошади. Оно всё ещё распознаётся как лошадь. Далее, давайте посмотрим на вот эту классную лошадку.
И она всё ещё правильно распознаётся как лошадь.
Эти красотки также были правильно распознаны.
Но вот эта всё ещё распознаётся неправильно. Но самое интересное, я думаю, вот эта женщина. Когда мы ранее использовали изображения 300х300 и больше свёрток, то она распознавалась правильно. Но сейчас нет. Это хороший пример важности проверки результатов обучения на большом проверочном наборе, с изучением мест, где результат ошибочный, и поиском способов исправить эту ситуацию. Использование такого уменьшенного в размере набора — дешевле в обучении, но тогда будут случаться ошибки, как с этой отвернувшейся женщиной и её скрытыми за платьем ногами, — потому что у нас нет этих данных в обучающем наборе. Это хорошая подсказка о том, как можно менять ваш набор данных, чтобы получить наилучший эффект при обучении.

16(w4)-Get Hands-on with compacted images (Lab 3): (15.MLg_1c)

(Практический опыт работы со сжатыми изображениями (лабораторная работа 3))
Try this version version of the notebook where Laurence compacted the images. You can see that training times will improve, but that some classifications might be wrong! Experiment with different sizes -- you don’t have to use 150x150 for example!
---------------------------------------------------------------
Попробуйте эту версию блокнота, где Лоуренс уплотнил изображения. Вы можете видеть, что время обучения улучшится, но некоторые классификации могут быть неправильными! Поэкспериментируйте с разными размерами — например, вам не обязательно использовать 150 x 150!

17(w4)- Week 4 Quiz: (15.MLg_1c)

1) Using Image Generator, how do you label images?:
1. You have to manually do it (-)
2. TensorFlow figures it out from the contents
3. It's based on the file name
4. It's based on the directory the image is contained in(+)
2) What method on the Image Generator is used to normalize the image?:
1. rescale(+)
2. Rescale_image
3. Normalize_image (-)
4. Normalize
3 )How did we specify the training size for the images?:
1. The training_size parameter on the training generator
2. The target_size parameter on the training generator(+)
3. The training_size parameter on the validation generator
4. The target_size parameter on the validation generator
4) When we specify the input_shape to be (300, 300, 3), what does that mean?:
1. There will be 300 horses and 300 humans, loaded in batches of 3
2. There will be 300 images, each size 300, loaded in batches of 3
3. Every Image will be 300x300 pixels, and there should be 3 Convolutional Layers
4. Every image will be 300x300 pixels, with 3 bytes to define color (+)
5) If your training data is close to 1.000 accuracy, but your validation data isn't, what's the risk here?:
1. You're overfitting on your validation data
2. No risk, that's a great result
3. You're overfitting on your training data (+)
4. You're everfittting on your validation data
6) Convolution Neural Networks are better for classifying images like horses and humans because:
1. There's a wide variety of horses (- +)
2. There's a wide variety of humans (- +)
3. In these images, the features may be in different parts of the frame (+)
7) After reducing the size of the images, the training results were different. Why?:
1. There was more condensed information in the images
2. There was less information in the images (-)
3. The training was faster
4. We removed some convolutions to handle the smaller images (+)

18(w4)- Lecture Notes Week 4: (15.MLg_1c)

(Конспект лекций, неделя 4)
The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.DeepLearning.AI
https://www.deeplearning.ai
makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/introduction-tensorflow/ungradedLti/3L0GK/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons License.DeepLearning.AI
https://www.deeplearning.ai
делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

19(w4)-Weekly Assignment: (15.MLg_1c)

Handling Complex Images (Обработка сложных изображений)
Now it is time to create your own image classifier for complex images. See if you can create a classifier for a set of happy or sad images.
To submit your Jupyter Notebook for grading, please click the Submit Assignment button while in the notebook.
IMPORTANT FOR SUCCESSFUL GRADING:
- Don't forget to save your notebook before submitting!
- Don't delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
Теперь пришло время создать собственный классификатор изображений для сложных изображений. Посмотрите, сможете ли вы создать классификатор для набора счастливых или грустных изображений.
Чтобы отправить блокнот Jupyter на оценку, нажмите кнопку «Отправить задание» в блокноте.
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не забудьте сохранить блокнот перед отправкой!
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

20(w4)-Wrap up: (15.MLg_1c)

Congratulations! You've reached the end of Course 1! You've come a long way from looking at the most basic of neural networks to building a basic computer vision neural network that classified clothing. You took this a little further by using convolutions that spot features in an image, and then classify and learn based on those features. In Course 2, you'll go a little deeper into convolutions by training networks with real-world images. You will also get to see many of the techniques used in challenges such as those run by Kaggle!
---------------------------------------------------------------
Поздравляем! Вы дошли до конца курса 1! Вы прошли долгий путь от изучения самых простых нейронных сетей до создания базовой нейронной сети компьютерного зрения, которая классифицировала одежду. Вы пошли немного дальше, используя свертки, которые обнаруживают функции на изображении, а затем классифицируют и изучают на основе этих функций. На курсе 2 вы немного углубитесь в свертки, обучая сети с изображениями реального мира. Вы также сможете увидеть многие методы, используемые в таких задачах, как те, которые проводит Kaggle!

21(w4)-video9: A conversation with Andrew (15.MLg_1c)

Congratulations on coming to the end of this first course, and well, you've come a long way. Yeah, I mean, we've looked at with the students like you looked at how to use TensorFlow, all the way from the beginning with doing something like fitting a straight line, to then like recognizing fashion items. It's really cool. It's like three lines of code to do a really complicated task like that. Isn't it amazing, computer vision in three lines like that? Then, we improve that by adding convolutions. We call it an improvement, but that means now four lines of code to define two conv layers and two maxpool layers, and then a two like TensorFlow take cares of a lot of the rest. Then, we looked at going beyond the simple images to bigger and colored images, and we didn't even add any lines of code for that, right? It was just changing the shape of the data coming in. Yeah. So by learning a framework like this, you can write very complicated programs with just a few lines of code, and this helps people save a lot of time. But there's still a lot more to learn. Oh there is, like some of the things that we'd love to explore are things such as, when you have very small data sets that can lead to an error called over-fitting. So we'll explore some techniques and tools that we can use to avoid that. Transfer learning. If you can download someone else's say TensorFlow model, and use that for your own problem, even though I was trained on a totally different data set, TensorFlow has tools that let you do that efficiently as well. Absolutely, and one of the things that a lot of AI practitioners love to be involved in is like this online competitions, where places like Kango provide a data set, and they ask you to build a classifier around that data set. We're going to explore some of the skills that you can use to take part in those competitions. So congratulations again on coming to the end of the first course and there's still all these amazing things to learn about TensorFlow. So please go on to the next course.
---------------------------------------------------------------
Поздравляю с тем, что вы дошли до конца этого первого курса, и да, вы прошли длинный путь. Да, мы увидели вместе со студентами, как использовать TensorFlow, на всём протяжении, от начала, когда делали что-то вроде нахождения прямой линии, — до таких вещей, как распознавание предметов одежды. Это очень круто. Всего три строчки кода, чтобы выполнить действительно сложную задачу вроде этой. Разве это не удивительно, компьютерное зрение в три строчки кода? Далее мы улучшили это, добавив свёртки. Мы называем это улучшением, но теперь это означает 4 строчки кода, чтобы определить 2 свёрточных слоя и 2 MaxPool слоя, и затем такой инструмент, как TensorFlow, позаботится обо всём остальном. Затем мы перешли от простых изображений к более крупным и цветным изображениям, и для этого даже не добавили ни одной строчки кода, верно? Мы просто изменили размерность входных данных. Так что изучив фреймворк, подобный этому, вы можете писать очень сложные программы, написав всего несколько строчек кода, и это помогает людям сэкономить кучу времени. Но ещё очень многое только предстоит изучить. Да, среди таких тем, которые мы хотели изучить, есть, например, то, что когда у вас очень маленькие наборы данных, то это может приводить к ошибке, называемой "переобучение". Поэтому мы будем изучать некоторые техники и инструменты, использование которых позволит нам этого избежать. И передача обучения. Если вы можете скачать скажем, чью-то модель TensorFlow, и использовать её для решения вашей задачи, даже если она была обучена на абсолютно другом наборе данных, то у TensorFlow также есть инструменты, которые позволят вам эффективно это сделать. Именно. И ещё одна вещь, в которой многие работающие с ИИ обожают принимать участие: это соревнования онлайн, где есть ресурсы вроде Kaggle, предоставляющие наборы данных, и они дают задание построить классификатор на основании этих данных. Мы собираемся рассмотреть некоторые из навыков, которые пригодятся для участия в этих соревнованиях. Итак, ещё раз поздравляю вас с тем, что дошли до конца первого курса, и впереди ещё множество потрясающих вещей в TensorFlow, которые предстоит изучить. Так что приглашаем вас перейти к следующему курсу.


16.MLg_2c


(w1) Exploring a Larger Dataset (16.MLg_2c)

(Изучение большего набора данных)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 17 minutes
Self-study: 52 minutes
Graded tasks (Tasks to be assessed): 2

(w1) Introduction: (16.MLg_2c)

In the first course in this specialization, you had an introduction to TensorFlow, and how, with its high level APIs you could do basic image classification, and you learned a little bit about Convolutional Neural Networks (ConvNets). In this course you'll go deeper into using ConvNets will real-world data, and learn about techniques that you can use to improve your ConvNet performance, particularly when doing image classification!In Week 1, this week, you'll get started by looking at a much larger dataset than you've been using thus far: The Cats and Dogs dataset which had been a Kaggle Challenge in image classification!
---------------------------------------------------------------
На первом курсе этой специализации вы познакомились с TensorFlow и узнали, как с его высокоуровневыми API-интерфейсами выполнять базовую классификацию изображений, а также немного узнали о сверточных нейронных сетях (ConvNets). В этом курсе вы углубитесь в использование ConvNets с реальными данными и узнаете о методах, которые вы можете использовать для повышения производительности ConvNet, особенно при классификации изображений! На этой неделе на первой неделе вы начнете с глядя на гораздо больший набор данных, чем вы использовали до сих пор: набор данных «Кошки и собаки», который был вызовом Kaggle в классификации изображений!

(w1) Learning Objectives: (16.MLg_2c)

● Gain understanding about Keras’ utilities for pre-processing image data, in particular the ImageDataGenerator class
● Develop helper functions to move files around the filesystem so that they can be fed to the ImageDataGenerator
● Learn how to plot training and validation accuracies to evaluate model performance
● Build a classifier using convolutional neural networks for performing cats vs dogs classification
---------------------------------------------------------------
● Получите представление об утилитах Keras для предварительной обработки данных изображений, в частности о классе ImageDataGenerator.
● Разработать вспомогательные функции для перемещения файлов по файловой системе, чтобы их можно было передать в ImageDataGenerator.
● Узнайте, как отображать точность обучения и проверки для оценки производительности модели.
● Создайте классификатор с использованием сверточных нейронных сетей для классификации кошек и собак.

1(w1)-video1: Introduction, A conversation with Andrew Ng (16.MLg_2c)

In the first course, you learned how to use TensorFlow to implement a basic neural network, going up all the way to basic Convolutional Neural Network. In this second course, you go much further. In the first week, you take the ideas you've learned, and apply them to a much bigger dataset of cats versus dogs on Kaggle. Yes so we take the full Kaggle dataset of 25,000 cats versus dogs images. In the last module, we looked at horses and humans, which was about 1,000 images. So we want to take a look at what it's like to train a much larger dataset, and that was like a data science challenge, not that long ago. Now, we're going to be learning that here, which I think is really cool In fact, we have substantially similar ideas as their previous goals, and apply it to much bigger datasets, and hopefully get great results. Yeah, we're hoping for good results. Let's see what the students get as they do some of the assignments with it as well. One of the things that working with a larger dataset, then helps with is over-fitting. So with a smaller dataset, you are at great risk of overfitting; with a larger dataset, then you have less risk of over-fitting, but overfitting can still happen. Pretty cool. Then in week 2, you'll learn another method for dealing with overfitting, which is that TensorFlow provides very easy to use tools for data augmentation, where you can, for example, take a picture of a cat, and if you take the mirror image of the picture of a cat, it still looks like a cat. So why not do that, and throw that into the training set. Exactly. Or for example, you might only have upright pictures of cats, but if the cat's lying down, or it's on its side, then one of the things you can do is rotate the image. So It's like part of the image augmentation, is rotation, skewing, flipping, moving it around the frame, those kind of things. One of the things I find really neat about it, is particularly if you're using a large public dataset, is then you flow all the images off directly, and the augmentation happens as it's flowing. So you're not editing the images themselves directly. You're not changing the dataset. It all just happens in memory. This is all done as part of TensorFlow's Image Generation [inaudible]? Exactly. That they'll learned about it in the second week. Yeah. So then too one of the other strategy, of course for avoiding overfitting, is to use existing models, and to have transfer learning. Yeah. So I don't think anyone has as much data as they wish, for the problems we really care about. So Transfer Learning, lets you download the neural network, that maybe someone else has trained on a million images, or even more than a million images. So take an inception network, that someone else has trained, download those parameters, and use that to bootstrap your own learning process, maybe with a smaller dataset. Exactly. That has been able to spot features that you may not have been able to spot in your dataset, so why not be able to take advantage of that and speed-up training yours. I particularly find that one interesting as you move forward. That to be able to build off of other people's work, the open nature of the AI community, I find is really exciting and that allows you to really take advantage of that and be a part of the community. Standing on the shoulders of giants. I use transfer learning all the time, so TensorFlow lets you do that easily [inaudible] open source. Then finally in the fourth week, Multicast learning. Rather than doing two classes, like horses verses humans, or cats verses dogs, what if you have more than two classes, like class five rock, paper, scissors, that would be three classes, or inception would be 1,000 classes. So that the techniques of moving from two to more than two, be it three or be it a 1,000, are very very similar. So we're going to look at those techniques and we'll look at the code for that. So and we have a rock, paper, scissors example, that you're going to be able to build off of. So in this second course, you take what you learned in the first course, but go much deeper. One last fun thing, Lawrence had seen this coffee mug into AI for everyone in the course, and he asked me to bring it. I love that course, so thank you so much. It's a great course, because it has got everything for people who are beginning; even people who are non-technical, all the way up to experts. So thank you for the mug, but is it okay if I say I spot a sports car in the course as well, would you bring that? I don't have one of those to bring to you. So I'm really excited about this course. Please go ahead and dive into the first of the materials for week 1.
---------------------------------------------------------------
На первом курсе вы узнали, как использовать TensorFlow для реализации базовой нейронной сети, вплоть до базовой сверточной нейронной сети. В этом втором курсе вы идете намного дальше. В первую неделю вы берете изученные идеи и применяете их к гораздо большему набору данных о кошках и собаках на Kaggle. Да, поэтому мы берем полный набор данных Kaggle из 25 000 изображений кошек и собак. В последнем модуле мы рассмотрели лошадей и людей, что составило около 1000 изображений. Итак, мы хотим взглянуть на то, каково это обучать гораздо больший набор данных, и не так давно это было похоже на задачу науки о данных. Теперь мы собираемся изучить это здесь, и я думаю, что это действительно здорово. На самом деле, у нас есть идеи, в значительной степени схожие с их предыдущими целями, и мы применяем их к гораздо большим наборам данных и, надеюсь, получим отличные результаты. Да, мы надеемся на хорошие результаты. Давайте посмотрим, что получают ученики, выполняя с ним некоторые задания. Одна из вещей, которая помогает при работе с большим набором данных, — это чрезмерная подгонка. Таким образом, с меньшим набором данных вы подвергаетесь большому риску переобучения; с большим набором данных у вас меньше риск переобучения, но переоснащение все же может произойти. Довольно круто. Затем на второй неделе вы изучите еще один метод борьбы с переоснащением, заключающийся в том, что TensorFlow предоставляет очень простые в использовании инструменты для увеличения данных, где вы можете, например, сфотографировать кошку, а если взять зеркало образ с изображением кота, он все равно похож на кота. Так почему бы не сделать это и добавить в тренировочный набор. Точно. Или, например, у вас могут быть только вертикальные изображения кошек, но если кошка лежит или лежит на боку, вы можете повернуть изображение. Так что это как часть увеличения изображения, это вращение, перекос, отражение, перемещение по кадру и тому подобное. Одна из вещей, которые я нахожу в этом очень удобным, особенно если вы используете большой общедоступный набор данных, заключается в том, что вы передаете все изображения напрямую, а увеличение происходит по мере их передачи. Таким образом, вы не редактируете сами изображения напрямую. Вы не меняете набор данных. Просто все происходит в памяти. Все это делается как часть генерации изображений TensorFlow [неразборчиво]? Точно. Что они узнают об этом на второй неделе. Ага. Таким образом, одна из других стратегий, конечно же, для предотвращения переобучения, заключается в использовании существующих моделей и трансферном обучении. Ага. Так что я не думаю, что у кого-то есть столько данных, сколько они хотят, для проблем, которые нас действительно волнуют. Итак, Transfer Learning позволяет вам загрузить нейронную сеть, которую, возможно, кто-то еще обучил на миллионе или даже большем миллионе изображений. Итак, возьмите начальную сеть, которую обучил кто-то другой, загрузите эти параметры и используйте их для запуска собственного процесса обучения, возможно, с меньшим набором данных. Точно. Это позволило обнаружить функции, которые вы, возможно, не смогли обнаружить в своем наборе данных, так почему бы не воспользоваться этим и не ускорить обучение. Я особенно нахожу это интересным, когда вы продвигаетесь вперед. Я нахожу, что возможность опираться на работу других людей, открытый характер сообщества ИИ действительно захватывает, и это позволяет вам действительно воспользоваться этим и стать частью сообщества. Стоя на плечах великанов. Я постоянно использую трансферное обучение, так что TensorFlow позволяет вам это легко сделать [неразборчиво] с открытым исходным кодом. Затем, наконец, на четвертой неделе многоадресное обучение. Вместо того, чтобы делать два класса, как лошади против людей или кошки против собак, что, если у вас есть более двух классов, например, пятый класс камень, ножницы, бумага, это будет три класса, или начальный уровень будет 1000 классов. Так что техники перехода от двух к более чем двум, будь то три или будь то 1000, очень и очень похожи. Итак, мы рассмотрим эти методы и код для этого. Итак, у нас есть пример камня, ножниц, бумаги, на основе которого вы сможете построить. Итак, на этом втором курсе вы берете то, чему научились на первом курсе, но идете намного глубже. И последнее забавное обстоятельство: Лоуренс увидел эту кофейную кружку для всех участников курса и попросил меня принести ее. Я люблю этот курс, так что большое спасибо. Это отличный курс, потому что в нем есть все для начинающих; даже люди, которые не являются техническими, вплоть до экспертов. Так что спасибо за кружку, но ничего, если я скажу, что замечу на поле и спортивную машину, ты принесешь ее? У меня нет ни одного из них, чтобы принести вам. Так что я очень взволнован этим курсом. Пожалуйста, продолжайте и погрузитесь в первый из материалов для недели 1

2(w1)-Where to find the notebooks for this course: (16.MLg_2c)

(Где найти тетради для этого курса)
All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You can simply click the Open in Colab badge at the top of the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this
Github repository
under the C2 folder.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/supplement/GXMYv/where-to-find-the-notebooks-for-this-course
If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
scikit-learn==1.0.1
pandas==1.1.5
matplotlib==3.2.2
seaborn==0.11.2
---------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы можете просто щелкнуть значок «Открыть в Colab» в верхней части неоцененных лабораторных работ, в то время как для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом
Репозиторий на гитхабе
в папке C2.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/supplement/GXMYv/где-найти-ноутбуки-для-этого-курса
Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

3(w1)-video2: A conversation with Andrew Ng (16.MLg_2c)

What does it take to download a public dataset off the Internet, like cats verses dogs, and get a neural network to work on it? Data is messy, sometimes you find surprising things like pictures of people holding cats or multiple cats or surprising things in data. In this week, you get to practice with using TensorFlow to deal with all of these issues. Yeah, and it's like, so even for example, you might have some files that are zero length and they could be corrupt as a results. So it's like using your Python skills, using your TensorFlow skills to be able to filter them out. Building a convolutional net to be able to spot things like you mentioned, a person holding it up. So that's some of the things we'll do this week, is by using, and it's still a very clean dataset that we're using with cats versus dogs, but you're going to hit some of those issues. I think you'll learn the skills that you need to be able to deal with other datasets that may not be as clean as this one. Yeah. Sometimes people think that AI is people like Lawrence and me sitting in front of a white board maybe a zen garden outside, talking about the future of humanity. The reality is, there's a lot of data cleaning, and having great tools to help with that data cleaning makes our workflow much more efficient. Definitely. So in this week, you get to practice all that, as well as train a pretty cool neural network to classify cats versus dogs. Please dive in.
---------------------------------------------------------------
Что нужно, чтобы скачать общедоступный набор данных с интернета, такой как "кошка или собака", и получить работающую на нём нейронную сеть? Данные неаккуратные, иногда вы находите удивительные вещи, такие, как картинки людей, которые держат кошку, или несколько кошек сразу, или другие сюрпризы в данных. На этой неделе вы получите практический урок использования TensorFlow для решения всех этих проблем. Да, и может быть даже, что если у вас встречаются файлы нулевой длины, возможно, потому что они повреждены. В таком случае, вы используете навыки в Python, используйте свои навыки в TensorFlow, чтобы отфильтровать такие картинки. Строите свёрточную сеть, чтобы замечать вещи, подобные упомянутым вами: как человек держит кошку. Это одна из тем, которыми мы займёмся на этой неделе, используя пока ещё очень чистый набор данных, мы используем "кошка или собака", — но вы столкнётесь с некоторыми из этих проблем. И, думаю, освоите навыки, необходимые вам, чтобы справиться с другими наборами данных, которые могут быть не такими чистыми. Да. Иногда люди думают, что ИИ — это когда люди, такие как Лоуренс и я, сидят перед маркерной доской, или, может, в дзенском саду, и говорят судьбах человечества. Но реальность в том, что нужно много очистки данных, и если у вас есть хорошие инструменты, помогающие очищать данные, то это сделает наш рабочий процесс намного более эффективным. Несомненно. Итак, на этой неделе вы получите практику в этой области и натренируете довольно крутую нейросеть, которая будет отличать кошек от собак. Погружайтесь в наш курс.

4(w1)-The cats vs dogs dataset: (16.MLg_2c)

In the next video, you'll look at the famous Kaggle Dogs v Cats dataset
https://www.kaggle.com/c/dogs-vs-cats
This was originally a challenge in building a classifier aimed at the world's best Machine Learning and AI Practitioners, but the technology has advanced so quickly, you'll see how you can do it in just a few minutes with some simple Convolutional Neural Network programming.
It's also a nice exercise in looking at a larger dataset, downloading and preparing it for training, as well as handling some preprocessing of data. Even data like this which has been carefully curated for you can have errors -- as you'll notice with some corrupt images!
Also, you may notice some warnings about missing or corrupt EXIF data as the images are being loaded into the model for training. Don't worry about this -- it won't impact your model! :)
---------------------------------------------------------------
В следующем видео вы увидите знаменитый набор данных Kaggle Dogs v Cats.
https://www.kaggle.com/c/dogs-vs-cats
Первоначально создание классификатора, предназначенного для лучших в мире специалистов по машинному обучению и искусственному интеллекту, было сложной задачей, но технология развивалась так быстро, что вы увидите, как это можно сделать всего за несколько минут с помощью простого программирования сверточной нейронной сети.
Это также хорошее упражнение для просмотра большого набора данных, его загрузки и подготовки к обучению, а также предварительной обработки данных. Даже такие данные, которые были тщательно подобраны для вас, могут содержать ошибки — как вы заметите на некоторых поврежденных изображениях!
Кроме того, вы можете заметить некоторые предупреждения об отсутствии или повреждении данных EXIF, поскольку изображения загружаются в модель для обучения. Не беспокойтесь об этом — это не повлияет на вашу модель! :)

5(w1)-video3: Training with the cats vs. dogs dataset (16.MLg_2c)

We've gone from the fashion dataset where the images were small and focused on the subject, to a new situation where we had images of horses and humans and action poses. We use convolutions to help us identify features in the image regardless of their location. This is a nice primer in solving some common data science problems on places like Kaggle. We'll next look at an old competition where you were encouraged to build a classifier to determine cats versus dogs. If you're not familiar with Kaggle, it's where ML challenges are posted often with prizes. Cats versus dogs was a famous one from a few years back. The techniques you've just learned can actually apply to that problem. So let's recap some of the concepts. One of the nice things with TensorFlow and Keras is that if you put your images into named subdirectories, an image generated will auto label them for you. So the cats and dogs dataset you could actually do that and you've already got a massive head start in building the classifier. Then you can subdivide that into a training set and a validation set. Then you can use image generators that appointed at those folders. To use an image generator, you should create an instance of one. If the data isn't already normalized, you can do that with the rescale parameter. You then call the flow from directory to get a generator object. For the training dataset, you will then point at the training directory and then specify the target size. In this case, the images are an all shapes and sizes. So we will resize them to 150 by 150 on the fly. We'll set the batch sizes to be 20. There's 2,000 images, so we'll use a 100 batches of 20 each. Because there are two classes that we want to classify for its still stays as a binary class mode. Similarly for validation, we set up a generator and pointed at the validation directory. We can explore the convolutions and pooling and the journey of the image through them. It's very similar to what you saw with the horses and humans. It has three sets of convolutions followed by pooling. Of course, the image is 150 by 150. Similarly, there's a single neuron with a sigmoid activation on the output. The summary of the layers is very similar to before but note that the size changes. We start with 150 by 150. So the convolution reduces that to 148 by 148. From there, we'll go until we end up with 17 by 17 that we feed into the dense layers. Compilation is as before. Now remember you can tweak the learning rate by adjusting the lr parameter. So now to train, and we can call model.fit generator and pass it the training generator and the validation generator. That's it. As you can see, it's very similar to what you built for horses versus humans. So let's see it in action.
---------------------------------------------------------------
Мы перешли от набора данных "fashion" [с предметами одежды - прим.], где изображения были маленькими, а предмет занимал большую часть кадра, — к новой ситуации, когда у нас есть изображения лошадей и людей в активных позах. Мы используем свёртку, чтобы найти признаки на изображениях, независимо от их местоположения. Это хорошая заготовка для решения некоторых популярных задач data science на площадках вроде Kaggle. А сейчас посмотрим на старый конкурс, в котором нужно было построить классификатор, отличающий кошек от собак. Если вы не знаете, что такое Kaggle, это сайт, на котором размещают конкурсы по машинному обучению, часто с призами. "Кошка или собака" был знаменитым конкурсом несколько лет назад. Приёмы, которые вы только что узнали, можно применить и к этой задачи. Так что давайте освежим некоторые понятия. Одна из замечательных особенностей TensorFlow и Keras — в том, что если вы раскладываете ваши изображения по подкаталогам, генератор изображений автоматически разметит их за вас. Можно поступить так и с "кошками и собаками", и у тогда у вас будет весомый задел для построения классификатора. Дальше вы можете разделить его на тренировочные и валидационные данные. Дальше вы можете запустить генератор изображений, указав ему эти каталоги. Чтобы использовать генератор изображений, вам надо создать объект этого класса. Если данные ещё не нормализованы, вы можете использовать параметр rescale. Затем вы вызываете flow_from_directory, чтобы получить объект генератора. Для тренировочного набора данных укажите на каталог с этим набором и укажете целевой размер. В таком случае, все изображения будут приведены к нужной форме и размеру. То есть, мы отмасштабируем их на лету к размеру 150x150. Мы установим размер группы равным 20. Всего есть 2000 изображений, так что будем использовать 100 групп по 20 элементов каждая. Поскольку мы хотим классифицировать по двум классам, по-прежнему установим бинарный режим. Для валидационного набора мы тем же образом создадим генератор и укажем ему каталог с валидационным набором. Мы можем исследовать свёртки и слияния, и то, как изображение проходит через них. Это очень похоже на то, что вы видели в случае с лошадьми и людьми. В сети есть три слоя свёртки, за каждым следует слой объединения. Конечно, изображения имеют размер 150x150. И так же [как с людьми/лошадьми - прим.] на выходе единственный нейрон с сигмоидной функцией активации. Сводка по слоям очень похожа на то, что было раньше, но обратите внимание, что размер изменился. Мы начинаем со 150x150. Свёртка уменьшает размер до 148x148. И мы продолжаем так, пока не доходим до размера 17x17, который мы отправляем в полносвязные слои. Компиляция происходит так же, как и раньше. Напоминаю, что вы можете настраивать скорость обучения, изменяя параметр lr. Пора тренировать модель, и мы можем вызвать метод model.fit_generator и передать в него генератор тренировочного набора и генератор валидационного набора. Вот и всё. Как видите, это очень похоже на то, что вы делали для лошадей и людей. Давайте посмотрим на это в действии.

6(w1)-Looking at the notebook (Lab 1): (16.MLg_2c)

Now that we’ve discussed what it’s like to extend to real-world data using the Cats vs Dogs dataset, let’s go into a notebook
that shows how to do the challenge for yourself. In the next video, you’ll see a screencast of this notebook in action. You’ll then be able to try it for yourself.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W1/ungraded_lab/C2_W1_Lab_1_cats_vs_dogs.ipynb
---------------------------------------------------------------
Теперь, когда мы обсудили, каково это расширять данные реального мира с помощью набора данных «Кошки против собак», давайте перейдем к блокноту.
который показывает, как сделать вызов для себя. В следующем видео вы увидите скринкаст этого ноутбука в действии. Тогда вы сможете попробовать это сами.

7(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community!: (16.MLg_2c)

Hello!
We’ve created a community for you to:
-Ask for help on assignments and other course content.
-Discuss course topics.
- Share your knowledge with other learners.
- Build your network
- Find out about exciting DeepLearning.AI news, events and competitions!
To go to the community for this course, tick the checkbox below indicating you agree to use the app responsibly, then click on the "Launch App” button.
If you are new to the community, click on the "Launch App" button to create your account and access our community.
We created this User Guide for you.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Be sure to check out the Code of Conduct community guidelines.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Having trouble accessing our community after clicking the “Launch App” button? Fill out this form to explain your issue and we will get back to you.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
We hope to see you in our community soon!
- The DeepLearning.AI team
This course uses a third-party app, [IMPORTANT] Have questions, issues or ideas? Join our Community!, to enhance your learning experience. The app will reference basic information like your name, email, and Coursera ID.
---------------------------------------------------------------
Привет!
Мы создали для вас сообщество, чтобы:
-Попросите помощи в заданиях и другом содержании курса.
-Обсудить темы курса.
- Поделитесь своими знаниями с другими учащимися.
- Создайте свою сеть
- Узнайте о захватывающих новостях, событиях и конкурсах DeepLearning.AI!
Чтобы перейти к сообществу для этого курса, установите флажок ниже, указывающий, что вы согласны использовать приложение ответственно, затем нажмите кнопку «Запустить приложение».
Если вы новичок в сообществе, нажмите кнопку «Запустить приложение», чтобы создать учетную запись и получить доступ к нашему сообществу.
Мы создали это Руководство пользователя для вас.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Обязательно ознакомьтесь с принципами сообщества Кодекса поведения.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Возникли проблемы с доступом к нашему сообществу после нажатия кнопки «Запустить приложение»? Заполните эту форму, чтобы объяснить вашу проблему, и мы свяжемся с вами.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
Надеемся скоро увидеть вас в нашем сообществе!
- Команда DeepLearning.AI
В этом курсе используется стороннее приложение. [ВАЖНО] Есть вопросы, проблемы или идеи? Присоединяйтесь к нашему сообществу!, чтобы улучшить свой опыт обучения. Приложение будет ссылаться на основную информацию, такую ​​как ваше имя, адрес электронной почты и идентификатор Coursera.

8(w1)-video4: Working through the notebook (16.MLg_2c)

The first thing we will do is download the set of images. They're stored as a zip file containing 3,000 images, 2,000 of which we'll use for training, and 1,000 for testing. Once they're downloaded, you'll need access to the underlying operating system of the virtual machine on which this Colab runs. This is available in the OS namespace. This code will unzip the cats and dogs data that you just downloaded, into the directory. In there, the sub-directories will be recreated, because they're stored that were in the zip file. The next thing is for us to set up our directories as variables, so we can point the generators at them. Now, that we have the directories as variables, we can pass them to the os.listdir to take the files from those directories, and load them into Python lists. We can see there's a list of file names like cat253.jpg, etc. On the files tab, we can also inspect the file system and we can see our cats versus dogs folder, within which we have training and validation sub-directories, which each contain cats and dogs directories. The images, of course, are stored in there. If we then count the images in each directory, we can be sure that we have the right amounts of images. As we can see, we have a thousand of each animal in Training and 500 of each in Tests for total of 3000. Next up, we can visualize some of the data, so we can see how diverse it is. This code would set a matplotlib which is a Python library for drawing graphics. This code will pick up some random cats and dogs and draw them in a grid. We can then see once it's drawn that there's a lot of diversity in these images. There's different colors of animal, there's different location within the picture, and there's even sometimes multiple items in the picture, like the lady here holding a cat. We can then run it again to see some more.
This image containing multiple cats is particularly challenging. Okay. Now, let's build our neural network. We'll import TensorFlow, and then we'll define our model. We'll print the summary, and here you can see the output shape of how the image passed through the layers, and gradually reducing in size through the convolution and pooling. Here, is where we compile our model, defining the loss function and the optimizer. Here, is where we set up the two generators, pointing them at the training and validation sub-directories. These contains sub-directories of their own, each with cats and dogs. When I run it, you'll see the printout. It found 2,000 images in two classes, and that's the training, and 1,000 images in two classes, that's the testing.
Now, we'll start the training and we'll watch it progress. It should take 3-3.5 minutes.
When it's done, you can see the accuracy is about 73% and it's not bad. It's not great but it's not bad. Okay. So let's take a look at how the model predicts on some images. So I'm going to choose these five images from my hard drive and upload them. Once they're uploaded, you can see that the classifier gives me a prediction on each. So let's now compare. This first one is really impressive and as you can see, the dog is in a very small part of the image and there's lots of other features like trees, mountains, skies and lakes, and the dog also has its face turned away, but the classifier still got it right. This one is obviously a dog, but again it's partially obscured. You can't see the body. It's just a white mass and the face while pronounced, is also hidden amongst the fur, but it got it right. This one's a bit more obvious, but it's also a very different looking dog than the previous one. The eyes, nose and mouth are all part of a dark patch, but the neural network still recognize the dog. This one's also very impressive. There are two cats in the image and one is mostly hidden, but that didn't confuse the model that correctly recognized the cat here. Strangely enough though, this is the one that the model got wrong. Maybe it's because we can only see one eye, or maybe the sharply defined branches to the left confused the model. So take a look, think about what you would do to go through this workbooks at this point and have some fun with it. Find some images of cats and dogs and upload them to the notebook and get it to classify them, then see if you can find one that you would expect to be easy that the prediction gets wrong. Once you've done that, see if you can edit that image in a way that gets it to work.
---------------------------------------------------------------
Сперва нам нужно скачать набор изображений. Они хранятся как zip-файл, содержащий 3000 изображений, 2000 из которых мы используем для тренировки, а 1000 — для тестирования. Когда они загрузятся, вам потребуется доступ к операционной системе виртуальной машины, на которой запущен Colab. Эта возможность есть в пространстве имён os. Данный код распакует данные "кошка или собака", которые вы только что скачали, в каталог /tmp. Также будут воссозданы подкаталоги, потому что по ним хранилось содержимое zip-файла. Далее нам необходимо задать наши каталоги как значения переменных, чтобы мы могли передать их в генераторы. Теперь, когда у нас есть имена каталогов в виде переменных, мы можем передать их здесь в os.list, чтобы получить списки файлов этих каталогов, загрузив их в списки Python. Как видим, у нас есть список имён файлов вроде cat253.jpg, и т.д.. Можно также посмотреть содержимое файловой системы во вкладке "Files", и в каталоге /tmp мы видим наш каталог "кошка или собака", внутри которого есть подкаталоги с тренировочными и валидационными данными, в каждом из которых есть каталоги "cats" и "dogs". Изображения, разумеется, хранятся в них. Если мы подсчитаем изображения в каждом каталоге, мы убедимся, что у нас нужное количество изображений. Как мы видим, у нас по тысяче изображений каждого животного в тренировочном наборе, и по 500 в тестовом, а всего 3000. Дальше мы можем визуализировать часть данных, чтобы увидеть, насколько они отличаются. Этот код настраивает matlpotlib — библиотеку Python для вывода графиков. Этот код выберет несколько случайных кошек и собак и выведет их в таблице. И тогда мы увидим, что изображения весьма разнообразны. У животных разный цвет, они находятся в разных местах кадра, и иногда даже на изображении есть несколько персонажей, например, женщина, держащая кошку. Затем мы можем запустить код ещё раз, чтобы увидеть ещё немного изображений.
Это изображение, на котором несколько кошек, — представляет особую сложность. Хорошо, теперь давайте строить нашу нейросеть. Мы импортируем TensorFlow и определим нашу модель. Мы выведем на экран сводку по модели, и в ней видно, как выходной размер по мере того, как изображение будет проходить через слои, постепенно уменьшается в размерах, проходя через свёртки и объединение. Здесь мы компилируем нашу модель, определяя функцию потерь и оптимизатор. Здесь мы настраиваем два генератора, указывая им подкаталоги с тренировочным и валидационным наборами. В каждом из них есть свои подкаталоги cats и dogs. Когда я запущу код, посмотрите, что он выведет. Он нашёл 2000 изображений двух классов, это тренировочный набор, и 1000 изображений двух классов — это тестовый набор. Теперь мы можем произвести обучение. В этот раз вместо того, чтобы использовать model.fit, мы снова используем model.fit_generator, потому что наши источники данных — генераторы. И вы видите, как мы их туда передаём. Теперь запустим обучение и будем следить за прогрессом. Обучение должно занять 3-3,5 минуты. Когда оно закончится, вы увидите, что точность около 73%, и это неплохо. Не слишком хорошо, но и неплохо. Хорошо, давайте теперь взглянем на предсказания модели на некоторых изображениях. Итак, я выберу эти пять изображений с моего жёсткого диска и загружу их. Когда они загрузятся, вы увидите, что классификатор даёт предсказания для каждого из них. Давайте теперь сравним. Мы видим, что для первого изображения предсказание явно неверное, но давайте сейчас посмотрим на каждое изображение, чтобы понять, можно ли сравнить результаты. Первое изображение действительно впечатляющее, потому что, как видите, собака занимает очень маленькую часть изображения, и на нём много разного: деревья, горы, небо, озеро, — а также собака отвернулась от нас, но классификатор всё равно дал верный ответ. Это определённо собака, но, опять-таки, она частично скрыта. Вы не видите тело. Это просто белое нечто, а морда, хотя и отчётливая, тоже маскируется шерстью, но результат здесь верный. Здесь всё несколько очевиднее, но при этом на вид сильно отличается от предыдущей собаки. Глаза, нос и рот — всё это части тёмного пятна, но нейросеть всё равно распознаёт собаку. Это изображение тоже очень впечатляющее. На нём две кошки, и одна почти скрыта, но это не смущает модель, которая корректно распознаёт кошку. Тем не менее, довольно удивительно, что на этом изображении модель ошибается. Возможно, потому что видно лишь один глаз, а может, резко очерченные ветки слева сбивают модель с толку. Итак, поизучайте, подумайте, что вы ещё можете сделать с этим блокнотом, и позанимайтесь с ним немного. Найдите несколько изображений кошек и собак, загрузите их в блокнот, и классифицируйте, а затем посмотрите, сможете ли вы найти такую картинку, чтобы она казалась простой, но предсказание оказалось бы ложным. Когда найдёте — посмотрите, получится ли у вас отредактировать это изображение так, чтобы модель заработала.

9(w1)-What you'll see next!: (16.MLg_2c)

In the last video, you saw a screencast of the notebook that shows how to build a classifier for Cats vs Dogs. You saw how, in some cases, it didn’t classify one cat correctly, and we asked you to try to figure out how you might fix it. In the next video, you’ll see one solution to this.
---------------------------------------------------------------
В последнем видео вы видели скринкаст блокнота, в котором показано, как построить классификатор для кошек против собак. Вы видели, как в некоторых случаях он неправильно классифицировал одну кошку, и мы попросили вас попытаться выяснить, как вы могли бы это исправить. В следующем видео вы увидите одно решение этой

10(w1)-video5: Fixing through cropping (16.MLg_2c)

Did you find a solution? Well, of course yours might be different from mine but let me show you what I did in the case of the cat my model thought was a dog. So let's go back to the notebook, and we'll run the code. I'll upload this image to see how it classifies. It's a crop of the cats, and lo and behold, it classifies as a cat. Let's open it, and compare it to the original image, and we'll see that just by cropping I was able to get it to change its classification. There must have been something in the uncropped image that matched features with a dog. Now I thought that was a very interesting experiment, didn't you? Now what do you think the impact of cropping might've had on training? Would that have trained the model to show that this was a cat better than an uncropped image. That's food for thought, and something to explore in the next lesson but first let's go back to the workbook.
---------------------------------------------------------------
Вы нашли решение? Конечно, ваше решение может отличаться от моего, но позвольте мне показать вам, что я делал в том случае, когда моя модель принимала кошку за собаку. Давайте вернёмся к блокноту и запустим код. Я загружаю это изображение, чтобы увидеть, как оно классифицируется. Это фрагмент изображения с кошкой и, как вы видите, классифицируется оно как кошка. Давайте откроем изображение и сравним с изначальным, и мы видим, что просто обрезав его, я смог изменить результат классификации. Должно быть что-то в необрезанном изображении, отвечавшее признакам собаки. И я думаю, что это был очень интересный эксперимент, не так ли? А что вы думаете о возможном влиянии обрезки на тренировку модели? Было бы лучше тренировать модель, указав этот вариант с кошкой, а не полное изображение? Это тема для размышлений и исследований на следующем уроке, но сперва вернёмся к блокноту.

11(w1)-video6: Visualizing the effect of the convolutions (16.MLg_2c)

Okay, in the previous video you took a look at a notebook that trained a convolutional neural network that classified cats versus dogs. Now let's take a look at how that worked.
Let's return to the notebook and take a look at the code that plots the outputs of the convolutions in max pooling layers. The key to this is understanding the model.layers API, which allows you to find the outputs and iterate through them, creating a visualization model for each one.
We can then load a random image into an array and pass it to the predict method of the visualization model.
The variable to keep an eye on is display_grid which can be constructed from x which is read as a feature map and processed a little for visibility in the central loop.
We'll then render each of the convolutions of the image, plus their pooling, then another convolution, etc.
You can see images such as the dog's nose being highlighted in many of the images on the left.
We can then run it again to get another random image. And while at first glance this appears to be a frog, if you look closely it's a Siamese cat with a dark head and dark paws towards the right of the frame. It's hard to see if any of the convolutions lock down on a feature. Except maybe the synonymous upright tail of the cat, we can see that vertical dark line in a number of the convolutions.
And let's give it one more try. We can see what's clearly a dog, and how the ears of the dog are represented very strongly. Features like this moving through the convolutions and being labeled as doglike could end up being called something like a floppy ear detector.
---------------------------------------------------------------
Итак, в предыдущем видео вы ознакомились с блокнотом, который тренировал свёрточную нейронную сеть, отличавшую кошек от собак. Давайте теперь посмотрим, как именно она работает.
Вернёмся к блокноту и посмотрим на код, отображающий выходы свёрток в объединяющие слои. Ключ к нему — в понимании программного интерфейса model.layers, который даёт вам возможность найти выходы [всех слоёв - прим.] и перечислять их, создавая для каждого модель визуализации.
Следите за переменной display_grid, которая создаётся из x, считываемого как карта признаков, и немного обрабатывается в самом вложенном цикле для наглядности.
Затем мы отображаем каждую из свёрток изображения, плюс слои объединения, затем следующая свёртка, и т.д..
Вы видите, что изображения, подобные собачьему носу, подсвечиваются на многих изображениях слева.
Мы можем запустить код ещё раз, чтобы взять другое случайное изображение. И хотя на первый взгляд это кажется лягушкой, но если вы внимательно присмотритесь, это сиамская кошка с тёмной головой и тёмными лапами в правой части кадра. Сложно увидеть, фиксирует ли признаки какая-либо из свёрток. Кроме, разве что, кошачьего хвоста справа вверху: мы видим тёмную вертикальную линию в череде свёрток.
Давайте сделаем ещё одну попытку. Мы явно видим собаку, и то, что собачьи уши отчётливо присутствуют. Таким признакам, проходящим сквозь свёртки и маркирующим сходство с собакой, можно даже дать название, вроде "индикатора висячих ушей".
Мы можем загрузить случайное изображение в виде массива, и передать его в метод predict модели визуализации.

12(w1)-video7: Looking at accuracy and loss (16.MLg_2c)

Before we go, let's have a quick look at plotting the learning history of this model. The object has training accuracy and loss values as well as validation accuracy and validation loss values. So let's iterate over these and plot them. Now, if you look closely, we didn't just call model.fit, we said history equals model.fit. So we now have a history object that we can query for data. Here you can see I'm using the same history object, and I'm calling its history property passing at ACC which gets me the model accuracy. When I run it and plot the training and validation accuracy, we can see that my training went towards one while my validation leveled out into 0.7 to 0.75 range. That shows that my model isn't bad, but I didn't really earn anything after just two epochs. It fits the training data very well with the validation data needed work. These results are borne out in the loss where we can see that after two epochs, my training loss went down nicely, but my validation loss climbed. So as it is, my model is about 75 percent accurate-ish after two epochs, and I don't really need to train any further. Remember also that we just used a subset of the full data. Using the entire dataset would likely yield better results. But before we do that, let's look at a few other options, and we'll do that in the next lesson.
---------------------------------------------------------------
Перед тем, как продолжить, давайте быстро взглянем на график истории обучения этой модели. В объекте истории хранятся точность и значение потерь как на тренировочном наборе, так и на валидационном. Давайте пройдёмся по этим значениям и построим их график. Если присмотреться, мы не просто вызвали model.fit, мы написали: history = model.fit(...) Так что у нас есть объект истории, к которому мы можем обратиться за данными. Как вы видите, я использую тот же самый объект истории, и я обращаюсь к его свойству history, передавая ключ acc, что даёт мне точность модели. Когда я запускаю код и вывожу график точности на тренировочном и валидационном наборах, видно, что точность на тренировочном наборе стремится к 1, а на валидационном остаётся между 0.7 и 0.75. Это говорит о том, что моя модель неплоха, но я не получаю никаких результатов уже после двух эпох обучения. Модель хорошо соответствует тренировочным данным, но над валидационными нужно работать. Эти выводы также видны на графике функции потерь: видно, как после двух эпох значение функции на тренировочном наборе быстро снижается, а на валидационном потери растут. Итак, моя модель точна на 75% после двух эпох, и дальнейшая тренировка ничего не даёт. Теперь вспомним, что мы использовали лишь подмножество всех данных. Использование полного набора, вероятно, даст лучшие результаты. Перед тем как приступить, давайте обратим внимание на некоторые другие варианты, поговорим о них на следующем уроке.

13(w1)-What have we seen so far?: (16.MLg_2c)

At the end of the last video, you saw how to explore the training history and discovered an interesting phenomenon: Even though the training data set’s accuracy went very high, we saw that after only a few epochs, the validation set leveled out. This is a clear sign that we are overfitting again. Using more data should help with this, but there are some other techniques that you can use with smaller data sets too. And we’ll see them in next week’s lesson!
---------------------------------------------------------------
В конце последнего видео вы увидели, как исследовать историю обучения, и обнаружили интересное явление: несмотря на то, что точность набора данных для обучения стала очень высокой, мы увидели, что всего через несколько эпох проверочный набор выровнялся. Это явный признак того, что мы снова переоснащаемся. Использование большего количества данных должно помочь в этом, но есть некоторые другие методы, которые вы можете использовать и с меньшими наборами данных. И мы увидим их на уроке на следующей неделе!

14(w1)- Week 1 Quiz: (16.MLg_2c)

1) What does flow_from_directory give you on the ImageDataGenerator?:
1. The ability to easily load images for training
2. The ability to pick the size of training images
3. The ability to automatically label images based on their directory name
4. All of the above (+)
2) If my Image is sized 150x150, and I pass a 3x3 Convolution over it, what size is the resulting image?:
1. 450x450
2. 153x153
3. 150x150(-)
4. 148x148(+)
3) If my data is sized 150x150, and I use Pooling if size 2X2, what size will the resulting image be?:
1. 300x300
2. 148x148
3. 149x149
4. 75x75 (+)
4) If I want to view the history of my training, how can I access it?:
1. Create a variable 'history and assign it to the return of model.fit or model.fit_generator (+)
2. Use a model.fit_generator (-)
3. Pass the parameter 'history=True' to the model.fit
4. Download the model and inspect it
5) What's the name of the API that allows you to inspect the impact of convolutions in the images?:
1. The model.convolutions API
2. The model.images API
3. The model.pools API
4. The model.layers API (+)
6) When exploring the graphs, the loss levelled out at about .75 after 2 epochs, but the accuracy climbed close to 1.0 after 15 epochs. What's the significance of this?:
1. There was no point training after 2 epochs, as we overfit to the validation data
2. There was no point training after 2 epochs, as we overfit to the taring data (+)
3. A bigger training set would give us better validation accuracy (-)
4. A bigger validation set would give us better training accuracy
7) Why is the validation accuracy a better indicator of model performance than training accuracy?:
1. It isn't, they're equally valuable
2. There's no relationship between them
3. The validation accuracy is based on images that the model hasn't been trained with, and this a better indicator of how the model will perform with new images(+)
4. The validation dateset is smaller, and this less accurate at measuring accuracy, so its performance isn't as important
8)Why is overfitting more likely to occur on smaller datasets?:
1. Because in a smaller dataset, your validation data is more likely to look like your training data.
2. Because there isn't enough data to activate all the convolutions or neurons
3. Because with less data, the training will take place more quickly, and some features may be missed
4. Because there's less likelihood of all possible features being encountered in the training process(+)

15(w1)-video8: Week 1 Wrap up (16.MLg_2c)

So you've now reached the end of week one. Congratulations. What I find really inspiring about this particular week was that what you've just done with the cats versus dogs datasets as a Kaggle data science challenge, not that long ago was really only available to the top view, the best researchers at the best universities. But now, thanks to the explosion in compute power, open datasets such as this one, and things such as TensorFlow, you're actually able to do this by yourself, on your own home computer. I find that really inspiring and really exciting. So thank you and get ready for week two.
---------------------------------------------------------------
Итак, вы дошли до конца первой недели. Поздравляю! Я считаю действительно вдохновляющим на этой неделе то, что вы справились с определением кошек и собак на наборе данных с соревнования Kaggle, а ведь это совсем недавно было доступно лишь верхушке, лучшим исследователям из лучших университетов. Но сейчас, благодаря взрывному росту вычислительной мощности, общедоступности наборов данных, таких, как этот, и вещам, подобным TensorFlow, — вы можете сделать это сами, на собственном домашнем компьютере. Я считаю это действительно вдохновляющим и захватывающим. Спасибо вам, и готовьтесь ко второй неделе.

16(w1)-Lecture Notes Week 1: (16.MLg_2c)

he lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
opyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes.
https://www.deeplearning.ai
You may make copies of these slides and use or distribute them for educational purposes as long as you cite
DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторском праве
Эти слайды распространяются по лицензии Creative Commons.
DeepLearning.AI делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях.
https://www.deeplearning.ai
Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы цитируете
DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные сведения о лицензии см.
https://creativecommons.org/licenses/by-sa/2.0/legalcode

17(w1)-Assignment Troubleshooting Tips: (16.MLg_2c)

(Советы по устранению неполадок с заданиями)
Here are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
1. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
2. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by following the instructions her. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/have-questions-meet-us-on-discourse
---------------------------------------------------------------
Ниже приведены некоторые общие рекомендации перед отправкой заданий по этому курсу. Пожалуйста, имейте это в виду не только для задания этой недели, но и для следующих:
1. Пожалуйста, не изменяйте код вне тегов START CODE HERE и END CODE HERE. Ваше решение должно быть размещено только между этими маркерами, чтобы гарантировать успешное оценивание. Изменение параметров функции и других тестовых ячеек, скорее всего, приведет к поломке оценщика. Если вы хотите поэкспериментировать с ними, вы можете сделать это после того, как успешно пройдете задание.
2. Если у вас есть дополнительные вопросы, создайте тему в сообществе Discourse, а не на дискуссионных форумах Coursera. Вы можете присоединиться, следуя ее инструкциям. Вы получите помощь там быстрее, потому что несколько наставников и ваших однокурсников следят за сообщениями. Просто убедитесь, что тема создана в правильной категории курса.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/have-questions-meet-us-on-discourse

18(w1)-Programming Assignment: Cats vs Dogs: (16.MLg_2c)

Instructions
This week, you explored a reduced version of the Cats v Dogs dataset and used it to train a convolutional neural network. You saw that it overfit very quickly, despite great results with the training set. One solution to overfitting is to use more data for both training and validation, and that’s this week’s exercise -- to build a classifier using the full Cats v Dogs dataset of 25k images!
Note again that when loading the images, you might get warnings about EXIF data being missing or corrupt. Don't worry about this -- it is missing data in the images, but it's not visual data that will impact the training.
Let's start building a classifier using the full Cats v Dogs dataset of 25k images.
---------------------------------------------------------------
инструкции
На этой неделе вы изучили сокращенную версию набора данных Cats v Dogs и использовали ее для обучения сверточной нейронной сети. Вы видели, что он очень быстро переобучается, несмотря на отличные результаты с тренировочным набором. Одним из решений переобучения является использование большего количества данных как для обучения, так и для проверки, и это упражнение на этой неделе — создать классификатор, используя полный набор данных «Кошки против собак» из 25 000 изображений!
Еще раз обратите внимание, что при загрузке изображений вы можете получить предупреждения об отсутствии или повреждении данных EXIF. Не беспокойтесь об этом — на изображениях отсутствуют данные, но это не визуальные данные, которые повлияют на обучение.
Давайте начнем создавать классификатор, используя полный набор данных Cats v Dogs из 25 000 изображений.
---------------------------------------------------------------
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
(Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.)
This notebook is hosted on Github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
(Эта записная книжка размещена на Github, поэтому для сохранения любых изменений вам необходимо создать ее копию на своем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».)
---------------------------------------------------------------
You should upload two files:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
create_train_val_dirs
split_data
train_val_generators
create_model
- The training history of your model (a file with .pkl extension) which will be used to grade the accuracy of your model.
---------------------------------------------------------------
Вы должны загрузить два файла:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
create_train_val_dirs
split_data
train_val_generators
create_model
- История обучения вашей модели (файл с расширением .pkl), которая будет использоваться для оценки точности вашей модели.
---------------------------------------------------------------
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.
---------------------------------------------------------------
If you have any questions about the assignments in this course, kindly ask for assistance in our community. If you haven't yet,lease click here and follow the instructions so you can join!
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community-on-discourse
---------------------------------------------------------------
Если у вас есть какие-либо вопросы о заданиях в этом курсе, пожалуйста, обратитесь за помощью в наше сообщество. Если вы еще этого не сделали, нажмите здесь и следуйте инструкциям, чтобы присоединиться!
---------------------------------------------------------------
How to submit
When you're ready to submit, you can upload files for each part of the assignment on the "My submissions" tab.
---------------------------------------------------------------
Как отправить
Когда вы будете готовы отправить, вы можете загрузить файлы для каждой части задания на вкладке «Мои материалы».

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# file = "c2_week1_Passigment.ipynb"

Original cat's directory has 12500 images
Original dog's directory has 12500 images

There are 11249 images of cats for training
There are 11249 images of dogs for training
There are 1250 images of cats for validation
There are 1250 images of dogs for validation

train_generator = train_datagen.flow_from_directory(batch_size=150,),  Epoch 15/15
                          1_.Conv2D(16,)  |  2_.Conv2D(32,)  |   3_.Conv2D(64,)  |  .Dense(256,)
-----------------------------------------------------------------------------------------------------------------
accuracy:      |           0,98    (16)   | 0,00    (32)   | 0,00    (64)   | 0,00    (256)   |
-----------------------------------------------------------------------------------------------------------------
val_accuracy: |           0,83    (00)   |  0,00    (00)   | 0,00    (00)   |  0,00    (00)   |
-----------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------
accuracy:      |           0,975   (16)   | 0,00    (16)   | 0,00    (16)   | 0,00    (256)   |
-----------------------------------------------------------------------------------------------------------------
val_accuracy: |           0,8    (00)   |  0,00    (00)   | 0,00    (00)   |  0,00    (00)   |
-----------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------
accuracy:      |           0,962    (8)   | 0,00    (16)   | 0,00    (32)   | 0,00    (256)   |
-----------------------------------------------------------------------------------------------------------------
val_accuracy: |           0,814    (00)   |  0,00    (00)   | 0,00    (00)   |  0,00    (00)   |
-----------------------------------------------------------------------------------------------------------------
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

NEXT week_2 (16.MLg_2c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2) Augmentation: A technique to avoid overfitting (16.MLg_2c)

(Аугментация: метод, позволяющий избежать переобучения)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 14 minutes
Self-study: 1,25 hour
Graded tasks (Tasks to be assessed): 2

(w2) Introduction: (16.MLg_2c)

You've heard the term overfitting a number of times to this point. Overfitting is simply the concept of being over specialized in training -- namely that your model is very good at classifying what it is trained for, but not so good at classifying things that it hasn't seen. In order to generalize your model more effectively, you will of course need a greater breadth of samples to train it on. That's not always possible, but a nice potential shortcut to this is Image Augmentation, where you tweak the training set to potentially increase the diversity of subjects it covers. You'll learn all about that this week!
---------------------------------------------------------------
Вы слышали термин «переобучение» несколько раз. Переобучение — это просто концепция чрезмерной специализации в обучении, а именно: ваша модель очень хорошо классифицирует то, для чего она обучена, но не так хорошо классифицирует то, чего она не видела. Чтобы более эффективно обобщить вашу модель, вам, конечно, потребуется большее количество выборок для ее обучения. Это не всегда возможно, но хороший потенциальный ярлык для этого — увеличение изображения, где вы настраиваете тренировочный набор, чтобы потенциально увеличить разнообразие предметов, которые он охватывает. Вы узнаете все об этом на этой неделе!

(w2) Learning Objectives: (16.MLg_2c)

● Recognize the impact of adding image augmentation to the training process, particularly in time
● Demonstrate overfitting or lack of by plotting training and validation accuracies
● Familiarize with the ImageDataGenerator parameters used for carrying out image augmentation
● Learn how to mitigate overfitting by using data augmentation techniques
---------------------------------------------------------------
● Признать влияние добавления увеличения изображения в учебный процесс, особенно во времени
● Продемонстрируйте переобучение или отсутствие, нанеся на график точность обучения и проверки.
● Ознакомьтесь с параметрами ImageDataGenerator, используемыми для увеличения изображения.
● Узнайте, как уменьшить переоснащение с помощью методов увеличения данных.

1(w2)-video1: (16.MLg_2c)

Image augmentation and data augmentation is one of the most widely used tools in deep learning to increase your dataset size and make your neural networks perform better. In this week, you'll learn how the use of the easy-to-use tools in TensorFlow to implement this. Yes. So like last week when we looked at cats versus dogs, we had 25,000 images. That was a nice big dataset, but we don't always have access to that. In fact, sometimes, 25,000 images isn't enough. Exactly. Some of the nice things with being able to do image augmentation is that we can then, I think you just use the term create new data, which is effectively what we're doing. So for example, if we have a cat and our cats in our training dataset are always upright and their ears are like this, we may not spot a cat that's lying down. But with augmentation, being able to rotate the image, or being able to skew the image, or maybe some other transforms would be able to effectively generate that data to train off. So you skew the image and just toss that into the training set. But there's an important trick to how you do this in TensorFlow as well to not take an image, warp it, skew it, and then blow up the memory requirements. So TensorFlow makes it really easy to do this. Yes. So you will learn a lot about the image generator and the image data generator, where the idea is that you're not going to edit the images directly on the drive. As they get float off the directory, then the augmentation will take place in memory as they're being loaded into the neural network for training. So if you're dealing with a dataset and you want to experiment with different augmentations, you're not overriding the data. So [inaudible] to generate a library lets you load it into memory and just in memory, process the images and then stream that to the training set to the neural network we'll ultimately learn on. This is one of the most important tricks that the deep learning [inaudible] realizes, really the preferred way these days to do image augmentation. Yeah and I think it's, for the main reason that it's not impacting your data, right, you're not overriding your data because you may need to experiment with that data again and those kind of things. It's also nice and fast. It doesn't blow up your memory requirements. You can take one image and create a lot of other images from it, but you don't want to save all those other images onto this. Remember, we had a conversation recently about the lack of, there's a lot of literature on this topic so there's opportunity to learn. Yeah. One of these thinkings about data augmentation and image augmentation is so many people do it, it's such an important part of how we train neural networks. At least today, the academic literature on it is thinner relative to what one might guess, given this importance, but this is definitely one of the techniques you should learn. So please dive into this week's materials to learn about image augmentation and data augmentation.
---------------------------------------------------------------
Аугментация изображений и аугментация данных — это один из наиболее широко используемых инструментов в глубоком обучении для того, чтобы увеличить размер вашего набора данных и заставить ваши нейросети работать лучше. На этой неделе вы научитесь использовать простой в использовании инструмент аугментации данных в TensorFlow. Да. Как и на прошлой неделе, когда мы различали кошек и собак, и у нас было 25 000 изображений. Это был большой и хороший набор данных, но у нас не всегда есть доступ к подобному. Вообще-то, иногда даже 25 000 изображений недостаточно. Точно. Одно из достоинств возможности аугментировать изображения состоит в том, что мы тогда можем... кажется, вы только что использовали термин "создавать новые данные", и он хорошо отражает то, что мы делаем. Например, если у нас есть кошка, и наши кошки в тренировочном наборе данных всегда ориентированы вверх, ушами вот так, то мы можем не обнаружить кошку, которая лежит. Но при помощи аугментации, имея возможность повернуть изображение или перекосить его, или внести какие-то ещё изменения, можно качественно генерировать такие данные для тренировки. Итак, вы перекашиваете изображение, и просто добавляете его в тренировочный набор. Но есть также одна важная деталь в том, как именно это делается в TensorFlow: не просто взять изображение, деформировать его, перекосить, и тем самым сильно раздуть требования к памяти. TensorFlow даёт возможность делать это чрезвычайно просто. Да. Итак, вы много узнаете про генератор изображений, про ImageDataGenerator, в котором важно то, что вы не редактируете изображения прямо на диске. По мере того, как они считываются из папки, аугментация данных происходит уже в памяти, в процессе их загрузки в нейросеть для тренировки. И если вы работаете с набором данных и хотите поэкспериментировать с различными методами аугментации данных, то вы не изменяете ваши данные. Итак, библиотека генерации изображений позволяет вам загрузить данные в память, и уже в памяти обрабатывать их, а затем отправлять в тренировочный набор для последующего обучения нейросети. Это один из наиболее важных приёмов, реализуемых в глубоком обучении, действительно самый предпочитаемый на сегодня метод — аугментация изображений. Да, и я думаю, главная тому причина — то, что она не влияет на ваши данные, вы не переписываете ваши данные, потому что вам может понадобиться экспериментировать с теми же самыми данными снова, и тому подобное. Это также красиво и быстро. И это не увеличивает ваши требования к памяти. Вы можете взять одно изображение, и сделать из него много других изображений, но вам не нужно сохранять все эти остальные изображения. Помните, у нас недавно был разговор о нехватке... при массе литературы по этому вопросу, это возможность учиться. Да. В аугментации данных и изображений интересно то, что так много людей делают ее, это настолько важная часть того, как мы тренируем нейросети. И, по крайней мере, сегодня в академической литературе она описана хуже, чем можно было бы предположить, принимая во внимание её важность, но это определённо один из методов, которые нужно выучить. Итак, приглашаем погрузиться в материалы этой недели, чтобы научиться аугментации данных и изображений.

2(w2)-Image Augmentation: (16.MLg_2c)

(Увеличение изображения)
You'll be looking a lot at Image Augmentation this week.
Image Augmentation is a very simple, but very powerful tool to help you avoid overfitting your data. The concept is very simple though: If you have limited data, then the chances of you having data to match potential future predictions is also limited, and logically, the less data you have, the less chance you have of getting accurate predictions for data that your model hasn't yet seen. To put it simply, if you are training a model to spot cats, and your model has never seen what a cat looks like when lying down, it might not recognize that in future.
Augmentation simply amends your images on-the-fly while training using transforms like rotation. So, it could 'simulate' an image of a cat lying down by rotating a 'standing' cat by 90 degrees. As such you get a cheap way of extending your dataset beyond what you have already.
To learn more about Augmentation, and the available transforms, check out https://keras.io/api/layers/preprocessing_layers/ --
and note that it's referred to as preprocessing for a very powerful reason: that it doesn't require you to edit your raw images, nor does it amend them for you on-disk. It does it in-memory as it's performing the training, allowing you to experiment without impacting your dataset.
---------------------------------------------------------------
На этой неделе вы будете много смотреть на Image Augmentation.
Image Augmentation — это очень простой, но очень мощный инструмент, который поможет вам избежать переобучения ваших данных. Однако концепция очень проста: если у вас ограниченные данные, то шансы на то, что у вас есть данные, соответствующие потенциальным будущим прогнозам, также ограничены, и логически, чем меньше у вас данных, тем меньше у вас шансов получить точные прогнозы для данных, которые ваша модель еще не видела. Проще говоря, если вы обучаете модель распознавать кошек, и ваша модель никогда не видела, как кошка выглядит лежа, она может не распознать это в будущем.
Расширение просто изменяет ваши изображения на лету во время обучения с использованием преобразований, таких как вращение. Таким образом, он мог «имитировать» изображение лежащей кошки, поворачивая «стоящую» кошку на 90 градусов. Таким образом, вы получаете дешевый способ расширить свой набор данных за пределы того, что у вас уже есть.
Чтобы узнать больше об дополнении и доступных преобразованиях, посетите https://keras.io/api/layers/preprocessing_layers/ --
и обратите внимание, что это называется предварительной обработкой по очень важной причине: она не требует редактирования необработанных изображений и не вносит в них изменения на диске. Он делает это в памяти во время обучения, позволяя вам экспериментировать, не влияя на ваш набор данных.

3(w2)-video2: (16.MLg_2c)

Introducing augmentation
To this point, we've been creating convolutional neural networks that train to recognize images in binary classes. Horses or humans, cats or dogs. They've worked quite well despite having relatively small amounts of data to train on. But we're at a risk of falling into a trap of overconfidence caused by overfitting. Namely, when the dataset is small, we have relatively few examples and as a result, we can have some mistakes in our classification. You've probably heard us use the term overfitting a lot and it's important to understand what that is. Think of it as being very good at spotting something from a limited dataset, but getting confused when you see something that doesn't match your expectations. So for example, imagine that these are the only shoes you've ever seen in your life. Then, you learn that these are shoes and this is what shoes look like. So if I were to show you these, you would recognize them as shoes even if they are different sizes than what you would expect. But if I were to show you this, even though it's a shoe, you would likely not recognize it as such. In that scenario, you have overfit in your understanding of what a shoe looks like. You weren't flexible enough to see this high-heel as a shoe because all of your training and all of your experience in what shoes look like are these hiking boots. Now, this is a common problem in training classifiers, particularly when you have limited data. If you think about it, you would need an infinite dataset to build a perfect classifier, but that might take a little too long to train. So in this lesson, I want to look at some tools that are available to you to make your smaller datasets more effective. We'll start with a simple concept, augmentation. When using convolutional neural networks, we've been passing convolutions over an image in order to learn particular features. Maybe it's the pointy ears for cat, two legs instead of four for human, that kind of thing. Convolutions have been very good at spotting these if they're clear and distinct in the image. But if we could go further, what if for example we could transform the image of the cat so that it could match other pictures of cats where the ears are oriented differently? So if the network was never trained for an image of a cat reclining like this, it may not recognize it. If you don't have the data for a cat reclining, then you could end up in an overfitting situation. But if your images are fed into the training with augmentation such as a rotation, the feature might then be spotted, even if you don't have a cat reclining, your upright cat when rotated, could end up looking the same.
---------------------------------------------------------------
К этому моменту мы уже создавали свёрточные нейросети, которые тренировали классифицировать изображения по двум классам. Лошади или люди, кошки или собаки. Они работали довольно неплохо, несмотря на то, что были натренированы на довольно небольшом наборе данных. Но мы рискуем попасть в ловушку чрезмерной уверенности, вызываемой переобучением. А именно, когда набор данных маленький, у нас относительно мало примеров, и в результате мы можем сделать при классификации некоторые ошибки. Вы, возможно, слышали, что мы часто используем термин "переобучение", и важно понимать, что это значит. Считайте, что это значит очень хорошо находить что-то нужное в ограниченном наборе данных, но сбиваться с толку, когда видишь что-то, не соответствующее твоим ожиданиям. Например, представьте, что это — единственная обувь, которую вы видели за свою жизнь. И вы усваиваете, что это обувь, и что обувь выглядит именно так. И если я покажу вам это, вы узнаете в этом обувь, даже если она не того размера, который вы ожидаете. Но если я покажу вам это, то хотя это и обувь — вы, скорее всего не признаете её таковой. В этом случае вы переобучились в своём понимании того, на что похожа обувь. Вы не были достаточно гибкими, чтобы увидеть в этих туфлях на каблуке обувь, поскольку всё ваше обучение и весь ваш опыт в том, на что похожа обувь, состоял только из туристических ботинок. Это распространённая проблема при тренировке классификаторов, особенно когда ваши данные ограничены в размерах. Если подумать, вам понадобится бесконечный набор данных, чтобы построить совершенный классификатор, но его тренировка может отнять слишком много времени. И в этом уроке я хочу рассмотреть некоторые инструменты, которые позволят вам сделать ваши небольшие наборы данных более эффективными. Мы начнём с простой идеи: с аугментации. Используя свёрточные нейросети, мы пропускаем изображения через свёртки, чтобы узнать конкретные признаки. Возможно, это острые уши у кошки, две ноги вместо четырёх у человека, и тому подобное. Свёртки очень хороши в нахождении таких признаков, если они отчётливо различимы на изображении. Но что, если пойти дальше, и, например, суметь изменить изображение кошки так, чтобы оно могло соответствовать другим изображениям кошек, на которых уши направлены в другую сторону? Если сеть никогда не тренировалась на изображении с кошкой, развалившейся таким образом, то она может не узнать её. Если у вас в наборе нет данных с разлёгшейся кошкой, вы можете попасть в ситуацию переобучения. Но если ваши изображения попадают на тренировку с аугментацией, такой, как поворот, то признак можно будет выделить, даже если у вас не было лежащей кошки. Ваша сидящая прямо кошка, будучи повёрнута, может выглядеть похоже.

4(w2)-Start Coding...: (16.MLg_2c)

Ok, now that we've looked at Image Augmentation implementation in Keras, let's dig down into the code.
You can see more about the different APIs at the Keras site here:
https://keras.io/preprocessing/image/
---------------------------------------------------------------
Хорошо, теперь, когда мы рассмотрели реализацию увеличения изображения в Keras, давайте углубимся в код.
Вы можете узнать больше о различных API на сайте Keras здесь:
https://keras.io/preprocessing/image/

5(w2)-video3: (16.MLg_2c)

Coding augmentation with ImageDataGenerator
So if you remember the image generator class that we used earlier, it actually has the ability to do this for you. Indeed, you have already done a little image augmentation with it when you're re-scaled upon loading. That saved you from converting all of your images on the file system and then loading them in, you just re-scaled on the fly. So let's take a look at some of the other options. Here's how you could use a whole bunch of image augmentation options with the image generator adding onto re-scale. Rotation range is a range from 0-180 degrees with which to randomly rotate images. So in this case, the image will rotate by random amount between 0 and 40 degrees. Shifting, moves the image around inside its frame. Many pictures have the subject centered. So if we train based on those kind of images, we might over-fit for that scenario. These parameters specify, as a proportion of the image size, how much we should randomly move the subject around. So in this case, we might offset it by 20 percent vertically or horizontally. Shearing is also quite powerful. So for example, consider the image on the right. We know that it's a person. But in our training set, we don't have any images of a person in that orientation. However, we do have an image like this one, where the person is oriented similarly. So if we shear that person by skewing along the x-axis, we'll end up in a similar pose. That's what the shear_range parameter gives us. It will shear the image by random amounts up to the specified portion in the image. So in this case, it will shear up to 20 percent of the image. Zoom can also be very effective. For example, consider the image on the right. It's obviously a woman facing to the right. Our image on the left is from the humans or horses training set. It's very similar but it zoomed out to see the full person. If we zoom in on the training image, we could end up with a very similar image to the one on the right. Thus, if we zoom while training, we could spot more generalized examples like this one. So you zoom with code like this. The 0.2 is a relative portion of the image you will zoom in on. So in this case, zooms will be a random amount up to 20 percent of the size of the image. Another useful tool is horizontal flipping. So for example, if you consider the picture on the right, we might not be able to classify it correctly as our training data doesn't have the image of a woman with her left hand raised, it does have the image on the left, where the subjects right arm is raised. So if the image were flipped horizontally, then it becomes more structurally similar to the image on the right and we might not over-fit to right arm raisers. To turn on random horizontal flipping, you just say horizontal_flip equals true and the images will be flipped at random. Finally, we just specify the fill mode. This fills in any pixels that might have been lost by the operations. I'm just going to stick with nearest here, which uses neighbors of that pixel to try and keep uniformity. Check the carets documentation for some other options. So that's the concept of image augmentation. Let's now take a look at cats versus dogs that are trained with and without augmentation, so that we can see the impact that this has.
---------------------------------------------------------------
Итак, если помните класс ImageGenerator, который мы использовали раньше, то он способен выполнить для вас аугментацию. И вы в действительности уже делали небольшую аугментацию изображений с его помощью, когда масштабировали изображение при загрузке. Это избавило вас от необходимости конвертировать все ваши изображения на диске, а потом загружать их в память, — вы просто масштабировали на лету. Итак, давайте посмотрим на некоторые варианты. Тут показано, как использовать целый букет настроек аугментации изображений для генератора изображений, вдобавок к масштабированию. rotation_range — это диапазон углов поворота от 0 до 180 градусов, на который случайным образом поворачивается изображение. В данном случае, изображение повернётся на случайный угол между 0 и 40 градусами. shift сдвигает изображение внутри кадра. На многих изображениях предмет находится в центре. Так что если мы тренируемся на таких изображениях, мы можем переобучиться под этот сценарий. Эти параметры указывают долю от размера изображения, на которую мы можем случайно сдвинуть предмет. В этом случае мы можем сдвинуть на 20% вертикально или горизонтально. Отображение сдвига — тоже довольно мощное. Например, возьмём изображение справа. Мы знаем, что это человек. Но в нашем тренировочном наборе у нас нет ни одного изображения человека в этой ориентации. Тем не менее, у нас есть такое изображение, как слева, где человек ориентирован похожим образом. Если мы сдвинем этого человека перекосом вдоль оси x, мы получим похожую позу. И это нам позволяет сделать параметр shear_range. Он сдвинет изображение на случайную величину в пределах указанной доли от изображения. В данном случае, он сдвинет на величину до 20% от размера изображения. Изменение поля зрения тоже может быть очень эффективным. Например, возьмём изображение справа. Это очевидно женщина, смотрящая направо. Наше изображение слева — из набора данных "человек или лошадь". Оно очень похоже, но сделано мелким планом, чтобы видеть всю фигуру человека. Если мы увеличим тренировочное изображение, то получим изображение, очень похожее на то, что справа. Таким образом, если мы меняем поле зрения, то можем получить более разнообразные случаи, как этот. Итак, используйте в вашем коде зум, как здесь: 0.2 — это доля изображения, на которую можно приближать или удалять. В данном случае, произойдёт зуммирование на случайную величину, до 20% от размера изображения. Ещё один полезный инструмент — горизонтальное отражение. Например, если взять изображение справа, то у нас может не выйти правильно его классифицировать, потому что в нашем тренировочном наборе нету изображения женщины с поднятой левой рукой, но есть изображение слева, где персонаж поднимает правую руку. Если изображение отразить горизонтально, оно будет более похоже по структуре на изображение справа, и мы можем избежать переобучения на персонажей с поднятой правой рукой. Чтобы включить случайное горизонтальное отражение, просто установите horisontal_flip=True, и часть изображений будет случайным образом отражена. Наконец, мы устанавливаем режим заливки. Он заполняет все пиксели, которые могут быть потеряны при преобразованиях. Я просто буду использовать заполнение "ближайшим", оно использует соседние пиксели для заполняемого, стараясь сохранить монотонность. Посмотрите в документацию, чтобы узнать о некоторых других возможностях. Вот такова идея аугментации изображений. Давайте сейчас посмотрим на сеть для набора "кошка или собака", натренированную с аугментацией и без неё, чтобы увидеть, насколько аугментация влияет.

6(w2)-Looking at the notebook (Lab 1): (16.MLg_2c)

Now that you've gotten to learn some of the basics of data augmentation, let's look at it in action in the Cats v Dogs classifier.
First, we'll run Cats v Dogs without augmentation, and explore how quickly it overfits.
If you want to run the notebook yourself, you can find it here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb
---------------------------------------------------------------
Теперь, когда вы изучили некоторые основы увеличения данных, давайте посмотрим на это в действии в классификаторе «Кошки против собак».
Во-первых, мы запустим игру «Кошки против собак» без аугментации и посмотрим, как быстро она переобучается.
Если вы хотите запустить блокнот самостоятельно, вы можете найти его здесь.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb

7(w2)-video4: (16.MLg_2c)

Demonstrating overfitting in cats vs. dogs
Let's take a look at training cats versus dogs with a smaller dataset over a longer cycle.
I'm going to start the training and we'll see it picked up the 2,000 training images, but note that we're training for 100 epochs.
After the first epoch, We'll watch the accuracy and validation accuracy figures.
Let's watch them for a few more epochs.
Keep an eye on those figures.
After eight epochs, the accuracy is approaching 0.8, but the validation accuracy has slowed its growth.
So now let's skip ahead to the end. I'm going to plot the accuracy and loss overall 100 epochs. We can see from this figure that the training reach close to a 100 percent accuracy in a little over 20 epochs. Meanwhile, the validation topped out at around 70 percent, and that's overfitting clearly been demonstrated. In other words, the neural network was terrific at finding a correlation between the images and labels of cats versus dogs for the 2,000 images that it was trained on, but once it tried to predict the images that it previously hadn't seen, it was about 70 percent accurate. It's a little bit like the example of the shoes we spoke about earlier. So in the next video, we'll take a look at the impact of adding augmentation to this.
---------------------------------------------------------------
Давайте посмотрим на тренировку "кошка или собака" с меньшим набором данных, но более длинным циклом. Сейчас я запущу тренировку, и мы увидим, как она выберет 2000 тренировочных изображений, но заметим, что мы тренируем в течение 100 эпох. После первой эпохи мы видим, что наша доля правильных ответов 0.5345, а на валидационном наборе 0.5290. Следите за этими числами. Давайте понаблюдаем за ними ещё несколько эпох. Мы смотрим на долю верных ответов в тренировочном и валидационном наборах. После восьми эпох доля правильных ответов приблизилась к 0.8, но на валидационном наборе она замедлила свой рост. А сейчас давайте перейдём прямо к концу. Я собираюсь вывести график доли верных ответов и функции потерь на протяжении всех 100 эпох. Мы видим из графика, что тренировка приблизилась к 100% доле верных ответов вскоре после 20-й эпохи. Тем временем, на валидационном наборе она колеблется вокруг 70%, и это явно показывает переобучение. Другими словами, нейросеть потрясающе точно находит корреляцию между изображениями и метками кошек и собак для тех 2000 изображений, на которых она тренировалась, но когда она пытается классифицировать изображения, которые ещё не видела, она даёт верный ответ в 70% случаев. Это немного похоже на пример с обувью, о котором мы говорили ранее. Так что, в следующем видео мы посмотрим, к какому эффекту приведёт здесь добавление аугментации.

8(w2)-The impact of augmentation on Cats vs. Dogs: (16.MLg_2c)

Now that we’ve seen it overfitting, let’s next look at how, with a simple code modification, we can add data augmentation to the same Convolutional Neural Network to see how it gives us better training data that overfits less. The notebook used in the next video will still be the one you just used in the previous screencast. Please re-open it if you want to follow along.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb
(repetition code from 6(w2)-Looking at the notebook (Lab 1):)
---------------------------------------------------------------
Теперь, когда мы увидели переоснащение, давайте теперь посмотрим, как с помощью простой модификации кода мы можем добавить увеличение данных к той же сверточной нейронной сети, чтобы увидеть, как это дает нам лучшие обучающие данные, которые меньше переобучаются. Ноутбук, использованный в следующем видео, по-прежнему будет тем, который вы только что использовали в предыдущем скринкасте. Пожалуйста, снова откройте его, если хотите продолжить.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb

9(w2)-video5: (16.MLg_2c)

Adding augmentation to cats vs. dogs
In the previous video, we looked at training a small data set of cats versus dogs, and saw how overfitting occurred relatively early on in the training, leading us to a false sense of security about how well the neural network could perform. Let's now take a look at the impact of adding image augmentation to the training. Here we have exactly the same code except that we've added the image augmentation code to it. I'll start the training, and we'll see that we have 2,000 training images in two classes. As we start training, we'll initially see that the accuracy is lower than with the non-augmented version we did earlier. This is because of the random effects of the different image processing that's being done. As it runs for a few more epochs, you'll see the accuracy slowly climbing. I'll skip forward to see the last few epochs, and by the time we reach the last one, our model's about 86 percent accurate on the training data, and about 81 percent on the test data. So let's plot this. We can see that the training and validation accuracy, and loss are actually in step with each other. This is a clear sign that we've solved the overfitting that we had earlier. While our accuracy is a little lower, it's also trending upwards so perhaps a more epochs will get us closer to 100 percent. Why don't you go ahead and give it a try?
---------------------------------------------------------------
В предыдущем видео мы смотрели на тренировку на небольшом наборе данных "кошка или собака", и видели, как переобучение произошло в процессе тренировки довольно рано, что привело нас к ложному чувству уверенности в том, насколько хорошо будет работать нейросеть. Давайте теперь посмотрим на эффект от добавления в тренировку аугментации изображений. Здесь у нас ровно тот же код, за исключением того, что мы добавили сюда код для аугментации изображений. Я начну тренировку, и мы увидим, что у нас есть 2000 тренировочных изображений, разбитых на два класса. Когда мы начали тренировку, то сначала видим, что доля верных ответов ниже, чем в неаугментированном варианте, который мы запускали ранее Это из-за воздействия случайных модификаций, производимых при обработке разных изображений. По мере прохождения ещё несколько эпох, вы увидите, что доля верных ответов понемногу растёт. Я перейду сразу к нескольким последним эпохам. К тому времени, как мы достигнем последней, доля верных ответов модели составит около 86% на тренировочных данных, и около 81% на тестовых данных. Давайте построим график. Мы видим, что тренировочная и валидационная доля верных ответов, как и значение функции потерь, по сути, следуют друг за другом. Это отчётливый признак того, что мы справились с переобучением, которое было раньше. В то время, как наша доля верных ответов немного ниже, у неё тенденция к возрастанию, так что, возможно, большее число эпох приблизит нас к 100%. Почему бы вам не пойти, и не проверить это?

10(w2)-Image Augmentation with Horses vs Humans! (Lab 2): (16.MLg_2c)

Having clearly seen the impact that augmentation gives to Cats vs Dogs, let’s now go back to the Horses vs Humans dataset from Course 1, and take a look to see if the augmentation algorithms will help there. Here’s the
notebook if you want to follow along with the next video.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_2_horses_v_humans_augmentation.ipynb
---------------------------------------------------------------
Ясно увидев влияние, которое аугментация оказывает на «Кошек против собак», давайте теперь вернемся к набору данных «Лошади против людей» из Курса 1 и посмотрим, помогут ли там алгоритмы аугментации. Вот
блокнот, если вы хотите следить за следующим видео.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_2_horses_v_humans_augmentation.ipynb

11(w2)-video6: (16.MLg_2c)

Exploring augmentation with horses vs. humans
Of course, image augmentation isn't the magic bullet to cure overfitting. It really helps to have a massive diversity of images. So for example, if we look at the horses or humans data set and train it for the same epochs, then we can take a look at its behavior. So I'm going to start training and show all 100 epochs. I sped it up a bit to save your time. As you watch, you'll see the test accuracy climbing steadily. At first, the validation accuracy seems to be in step, but then you'll see it varying wildly. What's happening here is that despite the image augmentation, the diversity of images is still too sparse and the validation set may also be poorly designed, namely that the type of image in it is too close to the images in the training set. If you inspect the data for yourself you'll see that's the case. For example, the humans are almost always standing up and in the center of the picture, in both the training and validation sets, so augmenting the image will change it to look like something that doesn't look like what's in the validation set. So by the time the training has completed, we can see the same pattern. The training accuracy is trending towards 100 percent, but the validation is fluctuating in the 60s and 70s. Let's plot this, we can see that the training accuracy climbs steadily in the way that we would want, but the validation fluctuated like crazy. So what we can learn from this is that the image augmentation introduces a random element to the training images but if the validation set doesn't have the same randomness, then its results can fluctuate like this. So bear in mind that you don't just need a broad set of images for training, you also need them for testing or the image augmentation won't help you very much.
---------------------------------------------------------------
Конечно, аугментация изображений — это не чудодейственное снадобье для лечения переобучения. Она действительно помогает получить большое разнообразие изображений. Например, если мы посмотрим на набор данных "лошадь или человек", и потренируем его такое же количество эпох, то сможем посмотреть на то, как это проявляется. Сейчас я начну тренировку и покажу все сто эпох. Я немного ускорю, чтобы сберечь вам время. По мере просмотра, вы видите, что доля верных ответов на тестовых данных стабильно растёт. Поначалу доля верных ответов на валидационных данных, кажется, отстаёт лишь на шаг, но далее вы увидите, как она будет сильно меняться. Здесь произошло то, что, вопреки аугментации изображений, разнообразие изображений всё ещё слишком слабое, а валидационный набор, возможно, плохо подобран, а именно, что изображения в нём слишком схожи по типу на те, что в тренировочном наборе. И если вы сами поразмыслите над данными, то поймёте, что причина в этом. Например, люди почти всегда стоят и находятся в центре изображения, как в тестовом, так и в валидационном наборе, — и тогда аугментация изображения изменяет их так, чтобы они выглядели чем-то непохожим на то, что есть в валидационном наборе. Итак, к моменту, когда тренировка завершена, мы видим ту же картину. Доля верных ответов на тренировочных данных стремится к 100%, а на валидационных колеблется около 60-70%. Давайте построим график. Мы видим, что доля верных ответов на тренировочных данных постоянно растёт, как нам и хотелось, но на валидационных данных она мечется, как сумасшедшая. Мы можем отсюда сделать вывод, что аугментация изображений вводит случайный элемент в тренировочные изображения, но если в валидационном наборе нет похожей случайности, тогда результат будет случайно колебаться, как здесь. Держите в уме, что вам не только нужен большой набор изображений для тренировки, он вам нужен также и для тестирования, в противном случае, аугментация изображений вам не особо поможет.

12(w2)-What have we seen so far?: (16.MLg_2c)

This week, you looked at the really useful tool that TensorFlow gives you with image augmentation. With it, you can effectively simulate a larger dataset from a smaller one with tools to move images around the frame, skew them, rotate them, and more. This can be an effective tool in fixing overfitting.
--------------------------------------------------------------
На этой неделе вы рассмотрели действительно полезный инструмент, который TensorFlow предоставляет вам для увеличения изображения. С его помощью вы можете эффективно имитировать больший набор данных из меньшего с помощью инструментов для перемещения изображений по кадру, их наклона, поворота и многого другого. Это может быть эффективным инструментом для устранения переобучения.

13(w2)- Week 2 Quiz: (16.MLg_2c)

1) How do you use Image Augmentation in TensorFlow:
1. You have to write a plugin to extend tf.layers
2. Using parameters to the ImageDataGenerator (+)
3. With the keras.augment API
4. With the tf.augment API
2) If me training data only has people facing left, but I want to classify people facing right, how would I avoid overfitting?:
1. Use the 'flip' parameter
2. Use the 'horizontal_flip' parameter(+)
3. Use the 'flip' parameter and set 'horizontal'
4. Use the 'flip_vertical' parameter around the Y axis
3) After adding data augmentation and using the same batch size and steps per epoch, you noticed that each training epoch became a little slower than when you trained without it. Why?:
1. Because the image preprocessing takes cycles (+)
2. Because the augmented data is bigger (-)
3. Because there is more data to train on
4. Because the training is making more mistakes
4) What does the fill_mode parameter do?:
1. There is no fill_mode parameter
2. It creates random noise in the image
3. It attempts to recreate lost information after a transformation like a shear(+)
4. It masks the background of an image
5) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk:
1. It gets overwritten, so be sure to make a backup
2. A copy is made and the augmentation is done on the copy
3. Nothing, all augmentation is done in-memory(+)
4. It gets deleted
6) How does Image Augmentation help solve overfitting?:
1. It slows down the training process
2. It manipulates the training set to generate more scenarios for features in the images (+)
3. It manipulates the validation set to generate more scenarios for features in the images
4. It automatically firs features to images by finding them through image processing techniques
7) When using Image Augmentation my training gets:
1. Slower (+)
2. Faster
3. Stays the Same
4. Much Faster
8) Using Image Augmentation effectively simulates having a larger data set for training:
1. False
2. True (+)

14(w2)-video7: (16.MLg_2c)

Week 2 Wrap up
So, congratulations on finishing week two. I hope you really enjoyed this week as much as I did, because image augmentation is frankly is one of my favorite things to play with in TensorFlow. I really enjoy the fact that when you have got a small dataset, like this one with the horses versus humans, that you're able to manipulate that dataset without changing the underlying images to open up whole new scenarios for training and to be able to train like we saw, like a man lying down or a woman facing left, and to be able to train for that even if you don't have those images in your training set. But next week, we're going to be doing something really exciting and that's called transfer learning. So, stay tuned.
--------------------------------------------------------------
Итак, поздравляю с окончанием второй недели. Я надеюсь, вам она так же понравилась, как и мне. Потому что, честно говоря, аугментация изображений — одна из тех вещей, с которыми мне нравится играть в TensorFlow. Мне по-настоящему нравится то, что когда у вас есть небольшой набор данных, как "лошадь или человек", то вы можете манипулировать этим набором без изменения изображений, на которых он основан, чтобы открывать целые новые сценарии для тренировки и, как мы видели, это даёт возможность тренировать на изображениях лежащего мужчины, или смотрящей влево женщины, — позволяет тренировать на них, даже если у вас нет этих изображений в вашем тренировочном наборе. Но на следующей неделе мы сделаем нечто действительно потрясающее — оно зовётся переносом обучения. Оставайтесь с нами.

15(w2)-Lecture Notes Week 2: (16.MLg_2c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI
https://www.deeplearning.ai
makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
or the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
--------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons.
Глубокое обучение.ИИ
https://www.deeplearning.ai
делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
или остальные детали лицензии см. https://creativecommons.org/licenses/by-sa/2.0/legalcode

16(w2)-Programming Assignment: Cats vs Dogs with Data Augmentation: (16.MLg_2c)

Now that you’ve seen Image Augmentation in action, it’s time to go back to the Cats v Dogs full Kaggle Challenge exercise. Last week you built a classifier for Cats v Dogs and trained it for a few epochs. This week I want you to add Augmentation to it, and experiment with different parameters to avoid overfitting. This will likely take a lot of time -- as it requires using the full dataset along with augmentation code to edit the data on-the-fly. The opportunity here is to try hard to get into State-of-the-Art type classification. Experiment with different images it hasn’t before seen, and see if you can get it to correctly classify them! For a particularly challenging image, see if you can get it to classify this one correctly:
https://pixabay.com/photos/bed-dog-animals-dogs-pets-relax-1284238/
--------------------------------------------------------------
Теперь, когда вы увидели увеличение изображения в действии, пришло время вернуться к полному упражнению Kaggle Challenge «Кошки против собак». На прошлой неделе вы создали классификатор для игры «Кошки против собак» и обучили его на несколько эпох. На этой неделе я хочу, чтобы вы добавили к нему аугментацию и поэкспериментировали с различными параметрами, чтобы избежать переобучения. Скорее всего, это займет много времени, поскольку для редактирования данных на лету требуется использование полного набора данных вместе с кодом дополнения. Возможность здесь состоит в том, чтобы изо всех сил стараться попасть в современную классификацию типов. Поэкспериментируйте с различными изображениями, которых он раньше не видел, и посмотрите, сможете ли вы заставить его правильно классифицировать их! Для особенно сложного изображения посмотрите, сможете ли вы правильно его классифицировать:
https://pixabay.com/photos/bed-dog-animals-dogs-pets-relax-1284238/
--------------------------------------------------------------
Lets now build the Cats vs. Dogs classifier using augmentation!
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/assignment/C2W2_Assignment.ipynb
--------------------------------------------------------------
Давайте теперь построим классификатор кошек против собак, используя аугментацию!
Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/assignment/C2W2_Assignment.ipynb
--------------------------------------------------------------
This notebook is hosted on github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
You should upload two files:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
create_train_val_dirs
split_data
train_val_generators
create_model
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
- The training history of your model (a file with .pkl extension) which will be used to grade the accuracy of your model.
--------------------------------------------------------------
Этот блокнот размещен на github, поэтому для сохранения любых изменений вам необходимо создать его копию на вашем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».
Вы должны загрузить два файла:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
create_train_val_dirs
split_data
train_val_generators
create_model
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.
- История обучения вашей модели (файл с расширением .pkl), которая будет использоваться для оценки точности вашей модели.

=======

NEXT week_2 (16.MLg_2c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2) Augmentation: A technique to avoid overfitting (16.MLg_2c)

(Аугментация: метод, позволяющий избежать переобучения)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 14 minutes
Self-study: 1,25 hour
Graded tasks (Tasks to be assessed): 2

(w2) Introduction: (16.MLg_2c)

You've heard the term overfitting a number of times to this point. Overfitting is simply the concept of being over specialized in training -- namely that your model is very good at classifying what it is trained for, but not so good at classifying things that it hasn't seen. In order to generalize your model more effectively, you will of course need a greater breadth of samples to train it on. That's not always possible, but a nice potential shortcut to this is Image Augmentation, where you tweak the training set to potentially increase the diversity of subjects it covers. You'll learn all about that this week!
---------------------------------------------------------------
Вы слышали термин «переобучение» несколько раз. Переобучение — это просто концепция чрезмерной специализации в обучении, а именно: ваша модель очень хорошо классифицирует то, для чего она обучена, но не так хорошо классифицирует то, чего она не видела. Чтобы более эффективно обобщить вашу модель, вам, конечно, потребуется большее количество выборок для ее обучения. Это не всегда возможно, но хороший потенциальный ярлык для этого — увеличение изображения, где вы настраиваете тренировочный набор, чтобы потенциально увеличить разнообразие предметов, которые он охватывает. Вы узнаете все об этом на этой неделе!

(w2) Learning Objectives: (16.MLg_2c)

● Recognize the impact of adding image augmentation to the training process, particularly in time
● Demonstrate overfitting or lack of by plotting training and validation accuracies
● Familiarize with the ImageDataGenerator parameters used for carrying out image augmentation
● Learn how to mitigate overfitting by using data augmentation techniques
---------------------------------------------------------------
● Признать влияние добавления увеличения изображения в учебный процесс, особенно во времени
● Продемонстрируйте переобучение или отсутствие, нанеся на график точность обучения и проверки.
● Ознакомьтесь с параметрами ImageDataGenerator, используемыми для увеличения изображения.
● Узнайте, как уменьшить переоснащение с помощью методов увеличения данных.

1(w2)-video1: (16.MLg_2c)

Image augmentation and data augmentation is one of the most widely used tools in deep learning to increase your dataset size and make your neural networks perform better. In this week, you'll learn how the use of the easy-to-use tools in TensorFlow to implement this. Yes. So like last week when we looked at cats versus dogs, we had 25,000 images. That was a nice big dataset, but we don't always have access to that. In fact, sometimes, 25,000 images isn't enough. Exactly. Some of the nice things with being able to do image augmentation is that we can then, I think you just use the term create new data, which is effectively what we're doing. So for example, if we have a cat and our cats in our training dataset are always upright and their ears are like this, we may not spot a cat that's lying down. But with augmentation, being able to rotate the image, or being able to skew the image, or maybe some other transforms would be able to effectively generate that data to train off. So you skew the image and just toss that into the training set. But there's an important trick to how you do this in TensorFlow as well to not take an image, warp it, skew it, and then blow up the memory requirements. So TensorFlow makes it really easy to do this. Yes. So you will learn a lot about the image generator and the image data generator, where the idea is that you're not going to edit the images directly on the drive. As they get float off the directory, then the augmentation will take place in memory as they're being loaded into the neural network for training. So if you're dealing with a dataset and you want to experiment with different augmentations, you're not overriding the data. So [inaudible] to generate a library lets you load it into memory and just in memory, process the images and then stream that to the training set to the neural network we'll ultimately learn on. This is one of the most important tricks that the deep learning [inaudible] realizes, really the preferred way these days to do image augmentation. Yeah and I think it's, for the main reason that it's not impacting your data, right, you're not overriding your data because you may need to experiment with that data again and those kind of things. It's also nice and fast. It doesn't blow up your memory requirements. You can take one image and create a lot of other images from it, but you don't want to save all those other images onto this. Remember, we had a conversation recently about the lack of, there's a lot of literature on this topic so there's opportunity to learn. Yeah. One of these thinkings about data augmentation and image augmentation is so many people do it, it's such an important part of how we train neural networks. At least today, the academic literature on it is thinner relative to what one might guess, given this importance, but this is definitely one of the techniques you should learn. So please dive into this week's materials to learn about image augmentation and data augmentation.
---------------------------------------------------------------
Аугментация изображений и аугментация данных — это один из наиболее широко используемых инструментов в глубоком обучении для того, чтобы увеличить размер вашего набора данных и заставить ваши нейросети работать лучше. На этой неделе вы научитесь использовать простой в использовании инструмент аугментации данных в TensorFlow. Да. Как и на прошлой неделе, когда мы различали кошек и собак, и у нас было 25 000 изображений. Это был большой и хороший набор данных, но у нас не всегда есть доступ к подобному. Вообще-то, иногда даже 25 000 изображений недостаточно. Точно. Одно из достоинств возможности аугментировать изображения состоит в том, что мы тогда можем... кажется, вы только что использовали термин "создавать новые данные", и он хорошо отражает то, что мы делаем. Например, если у нас есть кошка, и наши кошки в тренировочном наборе данных всегда ориентированы вверх, ушами вот так, то мы можем не обнаружить кошку, которая лежит. Но при помощи аугментации, имея возможность повернуть изображение или перекосить его, или внести какие-то ещё изменения, можно качественно генерировать такие данные для тренировки. Итак, вы перекашиваете изображение, и просто добавляете его в тренировочный набор. Но есть также одна важная деталь в том, как именно это делается в TensorFlow: не просто взять изображение, деформировать его, перекосить, и тем самым сильно раздуть требования к памяти. TensorFlow даёт возможность делать это чрезвычайно просто. Да. Итак, вы много узнаете про генератор изображений, про ImageDataGenerator, в котором важно то, что вы не редактируете изображения прямо на диске. По мере того, как они считываются из папки, аугментация данных происходит уже в памяти, в процессе их загрузки в нейросеть для тренировки. И если вы работаете с набором данных и хотите поэкспериментировать с различными методами аугментации данных, то вы не изменяете ваши данные. Итак, библиотека генерации изображений позволяет вам загрузить данные в память, и уже в памяти обрабатывать их, а затем отправлять в тренировочный набор для последующего обучения нейросети. Это один из наиболее важных приёмов, реализуемых в глубоком обучении, действительно самый предпочитаемый на сегодня метод — аугментация изображений. Да, и я думаю, главная тому причина — то, что она не влияет на ваши данные, вы не переписываете ваши данные, потому что вам может понадобиться экспериментировать с теми же самыми данными снова, и тому подобное. Это также красиво и быстро. И это не увеличивает ваши требования к памяти. Вы можете взять одно изображение, и сделать из него много других изображений, но вам не нужно сохранять все эти остальные изображения. Помните, у нас недавно был разговор о нехватке... при массе литературы по этому вопросу, это возможность учиться. Да. В аугментации данных и изображений интересно то, что так много людей делают ее, это настолько важная часть того, как мы тренируем нейросети. И, по крайней мере, сегодня в академической литературе она описана хуже, чем можно было бы предположить, принимая во внимание её важность, но это определённо один из методов, которые нужно выучить. Итак, приглашаем погрузиться в материалы этой недели, чтобы научиться аугментации данных и изображений.

2(w2)-Image Augmentation: (16.MLg_2c)

(Увеличение изображения)
You'll be looking a lot at Image Augmentation this week.
Image Augmentation is a very simple, but very powerful tool to help you avoid overfitting your data. The concept is very simple though: If you have limited data, then the chances of you having data to match potential future predictions is also limited, and logically, the less data you have, the less chance you have of getting accurate predictions for data that your model hasn't yet seen. To put it simply, if you are training a model to spot cats, and your model has never seen what a cat looks like when lying down, it might not recognize that in future.
Augmentation simply amends your images on-the-fly while training using transforms like rotation. So, it could 'simulate' an image of a cat lying down by rotating a 'standing' cat by 90 degrees. As such you get a cheap way of extending your dataset beyond what you have already.
To learn more about Augmentation, and the available transforms, check out https://keras.io/api/layers/preprocessing_layers/ --
and note that it's referred to as preprocessing for a very powerful reason: that it doesn't require you to edit your raw images, nor does it amend them for you on-disk. It does it in-memory as it's performing the training, allowing you to experiment without impacting your dataset.
---------------------------------------------------------------
На этой неделе вы будете много смотреть на Image Augmentation.
Image Augmentation — это очень простой, но очень мощный инструмент, который поможет вам избежать переобучения ваших данных. Однако концепция очень проста: если у вас ограниченные данные, то шансы на то, что у вас есть данные, соответствующие потенциальным будущим прогнозам, также ограничены, и логически, чем меньше у вас данных, тем меньше у вас шансов получить точные прогнозы для данных, которые ваша модель еще не видела. Проще говоря, если вы обучаете модель распознавать кошек, и ваша модель никогда не видела, как кошка выглядит лежа, она может не распознать это в будущем.
Расширение просто изменяет ваши изображения на лету во время обучения с использованием преобразований, таких как вращение. Таким образом, он мог «имитировать» изображение лежащей кошки, поворачивая «стоящую» кошку на 90 градусов. Таким образом, вы получаете дешевый способ расширить свой набор данных за пределы того, что у вас уже есть.
Чтобы узнать больше об дополнении и доступных преобразованиях, посетите https://keras.io/api/layers/preprocessing_layers/ --
и обратите внимание, что это называется предварительной обработкой по очень важной причине: она не требует редактирования необработанных изображений и не вносит в них изменения на диске. Он делает это в памяти во время обучения, позволяя вам экспериментировать, не влияя на ваш набор данных.

3(w2)-video2: (16.MLg_2c)

Introducing augmentation
To this point, we've been creating convolutional neural networks that train to recognize images in binary classes. Horses or humans, cats or dogs. They've worked quite well despite having relatively small amounts of data to train on. But we're at a risk of falling into a trap of overconfidence caused by overfitting. Namely, when the dataset is small, we have relatively few examples and as a result, we can have some mistakes in our classification. You've probably heard us use the term overfitting a lot and it's important to understand what that is. Think of it as being very good at spotting something from a limited dataset, but getting confused when you see something that doesn't match your expectations. So for example, imagine that these are the only shoes you've ever seen in your life. Then, you learn that these are shoes and this is what shoes look like. So if I were to show you these, you would recognize them as shoes even if they are different sizes than what you would expect. But if I were to show you this, even though it's a shoe, you would likely not recognize it as such. In that scenario, you have overfit in your understanding of what a shoe looks like. You weren't flexible enough to see this high-heel as a shoe because all of your training and all of your experience in what shoes look like are these hiking boots. Now, this is a common problem in training classifiers, particularly when you have limited data. If you think about it, you would need an infinite dataset to build a perfect classifier, but that might take a little too long to train. So in this lesson, I want to look at some tools that are available to you to make your smaller datasets more effective. We'll start with a simple concept, augmentation. When using convolutional neural networks, we've been passing convolutions over an image in order to learn particular features. Maybe it's the pointy ears for cat, two legs instead of four for human, that kind of thing. Convolutions have been very good at spotting these if they're clear and distinct in the image. But if we could go further, what if for example we could transform the image of the cat so that it could match other pictures of cats where the ears are oriented differently? So if the network was never trained for an image of a cat reclining like this, it may not recognize it. If you don't have the data for a cat reclining, then you could end up in an overfitting situation. But if your images are fed into the training with augmentation such as a rotation, the feature might then be spotted, even if you don't have a cat reclining, your upright cat when rotated, could end up looking the same.
---------------------------------------------------------------
К этому моменту мы уже создавали свёрточные нейросети, которые тренировали классифицировать изображения по двум классам. Лошади или люди, кошки или собаки. Они работали довольно неплохо, несмотря на то, что были натренированы на довольно небольшом наборе данных. Но мы рискуем попасть в ловушку чрезмерной уверенности, вызываемой переобучением. А именно, когда набор данных маленький, у нас относительно мало примеров, и в результате мы можем сделать при классификации некоторые ошибки. Вы, возможно, слышали, что мы часто используем термин "переобучение", и важно понимать, что это значит. Считайте, что это значит очень хорошо находить что-то нужное в ограниченном наборе данных, но сбиваться с толку, когда видишь что-то, не соответствующее твоим ожиданиям. Например, представьте, что это — единственная обувь, которую вы видели за свою жизнь. И вы усваиваете, что это обувь, и что обувь выглядит именно так. И если я покажу вам это, вы узнаете в этом обувь, даже если она не того размера, который вы ожидаете. Но если я покажу вам это, то хотя это и обувь — вы, скорее всего не признаете её таковой. В этом случае вы переобучились в своём понимании того, на что похожа обувь. Вы не были достаточно гибкими, чтобы увидеть в этих туфлях на каблуке обувь, поскольку всё ваше обучение и весь ваш опыт в том, на что похожа обувь, состоял только из туристических ботинок. Это распространённая проблема при тренировке классификаторов, особенно когда ваши данные ограничены в размерах. Если подумать, вам понадобится бесконечный набор данных, чтобы построить совершенный классификатор, но его тренировка может отнять слишком много времени. И в этом уроке я хочу рассмотреть некоторые инструменты, которые позволят вам сделать ваши небольшие наборы данных более эффективными. Мы начнём с простой идеи: с аугментации. Используя свёрточные нейросети, мы пропускаем изображения через свёртки, чтобы узнать конкретные признаки. Возможно, это острые уши у кошки, две ноги вместо четырёх у человека, и тому подобное. Свёртки очень хороши в нахождении таких признаков, если они отчётливо различимы на изображении. Но что, если пойти дальше, и, например, суметь изменить изображение кошки так, чтобы оно могло соответствовать другим изображениям кошек, на которых уши направлены в другую сторону? Если сеть никогда не тренировалась на изображении с кошкой, развалившейся таким образом, то она может не узнать её. Если у вас в наборе нет данных с разлёгшейся кошкой, вы можете попасть в ситуацию переобучения. Но если ваши изображения попадают на тренировку с аугментацией, такой, как поворот, то признак можно будет выделить, даже если у вас не было лежащей кошки. Ваша сидящая прямо кошка, будучи повёрнута, может выглядеть похоже.

4(w2)-Start Coding...: (16.MLg_2c)

Ok, now that we've looked at Image Augmentation implementation in Keras, let's dig down into the code.
You can see more about the different APIs at the Keras site here:
https://keras.io/preprocessing/image/
---------------------------------------------------------------
Хорошо, теперь, когда мы рассмотрели реализацию увеличения изображения в Keras, давайте углубимся в код.
Вы можете узнать больше о различных API на сайте Keras здесь:
https://keras.io/preprocessing/image/

5(w2)-video3: (16.MLg_2c)

Coding augmentation with ImageDataGenerator
So if you remember the image generator class that we used earlier, it actually has the ability to do this for you. Indeed, you have already done a little image augmentation with it when you're re-scaled upon loading. That saved you from converting all of your images on the file system and then loading them in, you just re-scaled on the fly. So let's take a look at some of the other options. Here's how you could use a whole bunch of image augmentation options with the image generator adding onto re-scale. Rotation range is a range from 0-180 degrees with which to randomly rotate images. So in this case, the image will rotate by random amount between 0 and 40 degrees. Shifting, moves the image around inside its frame. Many pictures have the subject centered. So if we train based on those kind of images, we might over-fit for that scenario. These parameters specify, as a proportion of the image size, how much we should randomly move the subject around. So in this case, we might offset it by 20 percent vertically or horizontally. Shearing is also quite powerful. So for example, consider the image on the right. We know that it's a person. But in our training set, we don't have any images of a person in that orientation. However, we do have an image like this one, where the person is oriented similarly. So if we shear that person by skewing along the x-axis, we'll end up in a similar pose. That's what the shear_range parameter gives us. It will shear the image by random amounts up to the specified portion in the image. So in this case, it will shear up to 20 percent of the image. Zoom can also be very effective. For example, consider the image on the right. It's obviously a woman facing to the right. Our image on the left is from the humans or horses training set. It's very similar but it zoomed out to see the full person. If we zoom in on the training image, we could end up with a very similar image to the one on the right. Thus, if we zoom while training, we could spot more generalized examples like this one. So you zoom with code like this. The 0.2 is a relative portion of the image you will zoom in on. So in this case, zooms will be a random amount up to 20 percent of the size of the image. Another useful tool is horizontal flipping. So for example, if you consider the picture on the right, we might not be able to classify it correctly as our training data doesn't have the image of a woman with her left hand raised, it does have the image on the left, where the subjects right arm is raised. So if the image were flipped horizontally, then it becomes more structurally similar to the image on the right and we might not over-fit to right arm raisers. To turn on random horizontal flipping, you just say horizontal_flip equals true and the images will be flipped at random. Finally, we just specify the fill mode. This fills in any pixels that might have been lost by the operations. I'm just going to stick with nearest here, which uses neighbors of that pixel to try and keep uniformity. Check the carets documentation for some other options. So that's the concept of image augmentation. Let's now take a look at cats versus dogs that are trained with and without augmentation, so that we can see the impact that this has.
---------------------------------------------------------------
Итак, если помните класс ImageGenerator, который мы использовали раньше, то он способен выполнить для вас аугментацию. И вы в действительности уже делали небольшую аугментацию изображений с его помощью, когда масштабировали изображение при загрузке. Это избавило вас от необходимости конвертировать все ваши изображения на диске, а потом загружать их в память, — вы просто масштабировали на лету. Итак, давайте посмотрим на некоторые варианты. Тут показано, как использовать целый букет настроек аугментации изображений для генератора изображений, вдобавок к масштабированию. rotation_range — это диапазон углов поворота от 0 до 180 градусов, на который случайным образом поворачивается изображение. В данном случае, изображение повернётся на случайный угол между 0 и 40 градусами. shift сдвигает изображение внутри кадра. На многих изображениях предмет находится в центре. Так что если мы тренируемся на таких изображениях, мы можем переобучиться под этот сценарий. Эти параметры указывают долю от размера изображения, на которую мы можем случайно сдвинуть предмет. В этом случае мы можем сдвинуть на 20% вертикально или горизонтально. Отображение сдвига — тоже довольно мощное. Например, возьмём изображение справа. Мы знаем, что это человек. Но в нашем тренировочном наборе у нас нет ни одного изображения человека в этой ориентации. Тем не менее, у нас есть такое изображение, как слева, где человек ориентирован похожим образом. Если мы сдвинем этого человека перекосом вдоль оси x, мы получим похожую позу. И это нам позволяет сделать параметр shear_range. Он сдвинет изображение на случайную величину в пределах указанной доли от изображения. В данном случае, он сдвинет на величину до 20% от размера изображения. Изменение поля зрения тоже может быть очень эффективным. Например, возьмём изображение справа. Это очевидно женщина, смотрящая направо. Наше изображение слева — из набора данных "человек или лошадь". Оно очень похоже, но сделано мелким планом, чтобы видеть всю фигуру человека. Если мы увеличим тренировочное изображение, то получим изображение, очень похожее на то, что справа. Таким образом, если мы меняем поле зрения, то можем получить более разнообразные случаи, как этот. Итак, используйте в вашем коде зум, как здесь: 0.2 — это доля изображения, на которую можно приближать или удалять. В данном случае, произойдёт зуммирование на случайную величину, до 20% от размера изображения. Ещё один полезный инструмент — горизонтальное отражение. Например, если взять изображение справа, то у нас может не выйти правильно его классифицировать, потому что в нашем тренировочном наборе нету изображения женщины с поднятой левой рукой, но есть изображение слева, где персонаж поднимает правую руку. Если изображение отразить горизонтально, оно будет более похоже по структуре на изображение справа, и мы можем избежать переобучения на персонажей с поднятой правой рукой. Чтобы включить случайное горизонтальное отражение, просто установите horisontal_flip=True, и часть изображений будет случайным образом отражена. Наконец, мы устанавливаем режим заливки. Он заполняет все пиксели, которые могут быть потеряны при преобразованиях. Я просто буду использовать заполнение "ближайшим", оно использует соседние пиксели для заполняемого, стараясь сохранить монотонность. Посмотрите в документацию, чтобы узнать о некоторых других возможностях. Вот такова идея аугментации изображений. Давайте сейчас посмотрим на сеть для набора "кошка или собака", натренированную с аугментацией и без неё, чтобы увидеть, насколько аугментация влияет.

6(w2)-Looking at the notebook (Lab 1): (16.MLg_2c)

Now that you've gotten to learn some of the basics of data augmentation, let's look at it in action in the Cats v Dogs classifier.
First, we'll run Cats v Dogs without augmentation, and explore how quickly it overfits.
If you want to run the notebook yourself, you can find it here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb
---------------------------------------------------------------
Теперь, когда вы изучили некоторые основы увеличения данных, давайте посмотрим на это в действии в классификаторе «Кошки против собак».
Во-первых, мы запустим игру «Кошки против собак» без аугментации и посмотрим, как быстро она переобучается.
Если вы хотите запустить блокнот самостоятельно, вы можете найти его здесь.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb

7(w2)-video4: (16.MLg_2c)

Demonstrating overfitting in cats vs. dogs
Let's take a look at training cats versus dogs with a smaller dataset over a longer cycle.
I'm going to start the training and we'll see it picked up the 2,000 training images, but note that we're training for 100 epochs.
After the first epoch, We'll watch the accuracy and validation accuracy figures.
Let's watch them for a few more epochs.
Keep an eye on those figures.
After eight epochs, the accuracy is approaching 0.8, but the validation accuracy has slowed its growth.
So now let's skip ahead to the end. I'm going to plot the accuracy and loss overall 100 epochs. We can see from this figure that the training reach close to a 100 percent accuracy in a little over 20 epochs. Meanwhile, the validation topped out at around 70 percent, and that's overfitting clearly been demonstrated. In other words, the neural network was terrific at finding a correlation between the images and labels of cats versus dogs for the 2,000 images that it was trained on, but once it tried to predict the images that it previously hadn't seen, it was about 70 percent accurate. It's a little bit like the example of the shoes we spoke about earlier. So in the next video, we'll take a look at the impact of adding augmentation to this.
---------------------------------------------------------------
Давайте посмотрим на тренировку "кошка или собака" с меньшим набором данных, но более длинным циклом. Сейчас я запущу тренировку, и мы увидим, как она выберет 2000 тренировочных изображений, но заметим, что мы тренируем в течение 100 эпох. После первой эпохи мы видим, что наша доля правильных ответов 0.5345, а на валидационном наборе 0.5290. Следите за этими числами. Давайте понаблюдаем за ними ещё несколько эпох. Мы смотрим на долю верных ответов в тренировочном и валидационном наборах. После восьми эпох доля правильных ответов приблизилась к 0.8, но на валидационном наборе она замедлила свой рост. А сейчас давайте перейдём прямо к концу. Я собираюсь вывести график доли верных ответов и функции потерь на протяжении всех 100 эпох. Мы видим из графика, что тренировка приблизилась к 100% доле верных ответов вскоре после 20-й эпохи. Тем временем, на валидационном наборе она колеблется вокруг 70%, и это явно показывает переобучение. Другими словами, нейросеть потрясающе точно находит корреляцию между изображениями и метками кошек и собак для тех 2000 изображений, на которых она тренировалась, но когда она пытается классифицировать изображения, которые ещё не видела, она даёт верный ответ в 70% случаев. Это немного похоже на пример с обувью, о котором мы говорили ранее. Так что, в следующем видео мы посмотрим, к какому эффекту приведёт здесь добавление аугментации.

8(w2)-The impact of augmentation on Cats vs. Dogs: (16.MLg_2c)

Now that we’ve seen it overfitting, let’s next look at how, with a simple code modification, we can add data augmentation to the same Convolutional Neural Network to see how it gives us better training data that overfits less. The notebook used in the next video will still be the one you just used in the previous screencast. Please re-open it if you want to follow along.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb
(repetition code from 6(w2)-Looking at the notebook (Lab 1):)
---------------------------------------------------------------
Теперь, когда мы увидели переоснащение, давайте теперь посмотрим, как с помощью простой модификации кода мы можем добавить увеличение данных к той же сверточной нейронной сети, чтобы увидеть, как это дает нам лучшие обучающие данные, которые меньше переобучаются. Ноутбук, использованный в следующем видео, по-прежнему будет тем, который вы только что использовали в предыдущем скринкасте. Пожалуйста, снова откройте его, если хотите продолжить.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_1_cats_v_dogs_augmentation.ipynb

9(w2)-video5: (16.MLg_2c)

Adding augmentation to cats vs. dogs
In the previous video, we looked at training a small data set of cats versus dogs, and saw how overfitting occurred relatively early on in the training, leading us to a false sense of security about how well the neural network could perform. Let's now take a look at the impact of adding image augmentation to the training. Here we have exactly the same code except that we've added the image augmentation code to it. I'll start the training, and we'll see that we have 2,000 training images in two classes. As we start training, we'll initially see that the accuracy is lower than with the non-augmented version we did earlier. This is because of the random effects of the different image processing that's being done. As it runs for a few more epochs, you'll see the accuracy slowly climbing. I'll skip forward to see the last few epochs, and by the time we reach the last one, our model's about 86 percent accurate on the training data, and about 81 percent on the test data. So let's plot this. We can see that the training and validation accuracy, and loss are actually in step with each other. This is a clear sign that we've solved the overfitting that we had earlier. While our accuracy is a little lower, it's also trending upwards so perhaps a more epochs will get us closer to 100 percent. Why don't you go ahead and give it a try?
---------------------------------------------------------------
В предыдущем видео мы смотрели на тренировку на небольшом наборе данных "кошка или собака", и видели, как переобучение произошло в процессе тренировки довольно рано, что привело нас к ложному чувству уверенности в том, насколько хорошо будет работать нейросеть. Давайте теперь посмотрим на эффект от добавления в тренировку аугментации изображений. Здесь у нас ровно тот же код, за исключением того, что мы добавили сюда код для аугментации изображений. Я начну тренировку, и мы увидим, что у нас есть 2000 тренировочных изображений, разбитых на два класса. Когда мы начали тренировку, то сначала видим, что доля верных ответов ниже, чем в неаугментированном варианте, который мы запускали ранее Это из-за воздействия случайных модификаций, производимых при обработке разных изображений. По мере прохождения ещё несколько эпох, вы увидите, что доля верных ответов понемногу растёт. Я перейду сразу к нескольким последним эпохам. К тому времени, как мы достигнем последней, доля верных ответов модели составит около 86% на тренировочных данных, и около 81% на тестовых данных. Давайте построим график. Мы видим, что тренировочная и валидационная доля верных ответов, как и значение функции потерь, по сути, следуют друг за другом. Это отчётливый признак того, что мы справились с переобучением, которое было раньше. В то время, как наша доля верных ответов немного ниже, у неё тенденция к возрастанию, так что, возможно, большее число эпох приблизит нас к 100%. Почему бы вам не пойти, и не проверить это?

10(w2)-Image Augmentation with Horses vs Humans! (Lab 2): (16.MLg_2c)

Having clearly seen the impact that augmentation gives to Cats vs Dogs, let’s now go back to the Horses vs Humans dataset from Course 1, and take a look to see if the augmentation algorithms will help there. Here’s the
notebook if you want to follow along with the next video.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_2_horses_v_humans_augmentation.ipynb
---------------------------------------------------------------
Ясно увидев влияние, которое аугментация оказывает на «Кошек против собак», давайте теперь вернемся к набору данных «Лошади против людей» из Курса 1 и посмотрим, помогут ли там алгоритмы аугментации. Вот
блокнот, если вы хотите следить за следующим видео.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/ungraded_labs/C2_W2_Lab_2_horses_v_humans_augmentation.ipynb

11(w2)-video6: (16.MLg_2c)

Exploring augmentation with horses vs. humans
Of course, image augmentation isn't the magic bullet to cure overfitting. It really helps to have a massive diversity of images. So for example, if we look at the horses or humans data set and train it for the same epochs, then we can take a look at its behavior. So I'm going to start training and show all 100 epochs. I sped it up a bit to save your time. As you watch, you'll see the test accuracy climbing steadily. At first, the validation accuracy seems to be in step, but then you'll see it varying wildly. What's happening here is that despite the image augmentation, the diversity of images is still too sparse and the validation set may also be poorly designed, namely that the type of image in it is too close to the images in the training set. If you inspect the data for yourself you'll see that's the case. For example, the humans are almost always standing up and in the center of the picture, in both the training and validation sets, so augmenting the image will change it to look like something that doesn't look like what's in the validation set. So by the time the training has completed, we can see the same pattern. The training accuracy is trending towards 100 percent, but the validation is fluctuating in the 60s and 70s. Let's plot this, we can see that the training accuracy climbs steadily in the way that we would want, but the validation fluctuated like crazy. So what we can learn from this is that the image augmentation introduces a random element to the training images but if the validation set doesn't have the same randomness, then its results can fluctuate like this. So bear in mind that you don't just need a broad set of images for training, you also need them for testing or the image augmentation won't help you very much.
---------------------------------------------------------------
Конечно, аугментация изображений — это не чудодейственное снадобье для лечения переобучения. Она действительно помогает получить большое разнообразие изображений. Например, если мы посмотрим на набор данных "лошадь или человек", и потренируем его такое же количество эпох, то сможем посмотреть на то, как это проявляется. Сейчас я начну тренировку и покажу все сто эпох. Я немного ускорю, чтобы сберечь вам время. По мере просмотра, вы видите, что доля верных ответов на тестовых данных стабильно растёт. Поначалу доля верных ответов на валидационных данных, кажется, отстаёт лишь на шаг, но далее вы увидите, как она будет сильно меняться. Здесь произошло то, что, вопреки аугментации изображений, разнообразие изображений всё ещё слишком слабое, а валидационный набор, возможно, плохо подобран, а именно, что изображения в нём слишком схожи по типу на те, что в тренировочном наборе. И если вы сами поразмыслите над данными, то поймёте, что причина в этом. Например, люди почти всегда стоят и находятся в центре изображения, как в тестовом, так и в валидационном наборе, — и тогда аугментация изображения изменяет их так, чтобы они выглядели чем-то непохожим на то, что есть в валидационном наборе. Итак, к моменту, когда тренировка завершена, мы видим ту же картину. Доля верных ответов на тренировочных данных стремится к 100%, а на валидационных колеблется около 60-70%. Давайте построим график. Мы видим, что доля верных ответов на тренировочных данных постоянно растёт, как нам и хотелось, но на валидационных данных она мечется, как сумасшедшая. Мы можем отсюда сделать вывод, что аугментация изображений вводит случайный элемент в тренировочные изображения, но если в валидационном наборе нет похожей случайности, тогда результат будет случайно колебаться, как здесь. Держите в уме, что вам не только нужен большой набор изображений для тренировки, он вам нужен также и для тестирования, в противном случае, аугментация изображений вам не особо поможет.

12(w2)-What have we seen so far?: (16.MLg_2c)

This week, you looked at the really useful tool that TensorFlow gives you with image augmentation. With it, you can effectively simulate a larger dataset from a smaller one with tools to move images around the frame, skew them, rotate them, and more. This can be an effective tool in fixing overfitting.
--------------------------------------------------------------
На этой неделе вы рассмотрели действительно полезный инструмент, который TensorFlow предоставляет вам для увеличения изображения. С его помощью вы можете эффективно имитировать больший набор данных из меньшего с помощью инструментов для перемещения изображений по кадру, их наклона, поворота и многого другого. Это может быть эффективным инструментом для устранения переобучения.

13(w2)- Week 2 Quiz: (16.MLg_2c)

1) How do you use Image Augmentation in TensorFlow:
1. You have to write a plugin to extend tf.layers
2. Using parameters to the ImageDataGenerator (+)
3. With the keras.augment API
4. With the tf.augment API
2) If me training data only has people facing left, but I want to classify people facing right, how would I avoid overfitting?:
1. Use the 'flip' parameter
2. Use the 'horizontal_flip' parameter(+)
3. Use the 'flip' parameter and set 'horizontal'
4. Use the 'flip_vertical' parameter around the Y axis
3) After adding data augmentation and using the same batch size and steps per epoch, you noticed that each training epoch became a little slower than when you trained without it. Why?:
1. Because the image preprocessing takes cycles (+)
2. Because the augmented data is bigger (-)
3. Because there is more data to train on
4. Because the training is making more mistakes
4) What does the fill_mode parameter do?:
1. There is no fill_mode parameter
2. It creates random noise in the image
3. It attempts to recreate lost information after a transformation like a shear(+)
4. It masks the background of an image
5) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk:
1. It gets overwritten, so be sure to make a backup
2. A copy is made and the augmentation is done on the copy
3. Nothing, all augmentation is done in-memory(+)
4. It gets deleted
6) How does Image Augmentation help solve overfitting?:
1. It slows down the training process
2. It manipulates the training set to generate more scenarios for features in the images (+)
3. It manipulates the validation set to generate more scenarios for features in the images
4. It automatically firs features to images by finding them through image processing techniques
7) When using Image Augmentation my training gets:
1. Slower (+)
2. Faster
3. Stays the Same
4. Much Faster
8) Using Image Augmentation effectively simulates having a larger data set for training:
1. False
2. True (+)

14(w2)-video7: (16.MLg_2c)

Week 2 Wrap up
So, congratulations on finishing week two. I hope you really enjoyed this week as much as I did, because image augmentation is frankly is one of my favorite things to play with in TensorFlow. I really enjoy the fact that when you have got a small dataset, like this one with the horses versus humans, that you're able to manipulate that dataset without changing the underlying images to open up whole new scenarios for training and to be able to train like we saw, like a man lying down or a woman facing left, and to be able to train for that even if you don't have those images in your training set. But next week, we're going to be doing something really exciting and that's called transfer learning. So, stay tuned.
--------------------------------------------------------------
Итак, поздравляю с окончанием второй недели. Я надеюсь, вам она так же понравилась, как и мне. Потому что, честно говоря, аугментация изображений — одна из тех вещей, с которыми мне нравится играть в TensorFlow. Мне по-настоящему нравится то, что когда у вас есть небольшой набор данных, как "лошадь или человек", то вы можете манипулировать этим набором без изменения изображений, на которых он основан, чтобы открывать целые новые сценарии для тренировки и, как мы видели, это даёт возможность тренировать на изображениях лежащего мужчины, или смотрящей влево женщины, — позволяет тренировать на них, даже если у вас нет этих изображений в вашем тренировочном наборе. Но на следующей неделе мы сделаем нечто действительно потрясающее — оно зовётся переносом обучения. Оставайтесь с нами.

15(w2)-Lecture Notes Week 2: (16.MLg_2c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI
https://www.deeplearning.ai
makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
or the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
--------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons.
Глубокое обучение.ИИ
https://www.deeplearning.ai
делает эти слайды доступными для образовательных целей. Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
или остальные детали лицензии см. https://creativecommons.org/licenses/by-sa/2.0/legalcode

16(w2)-Programming Assignment: Cats vs Dogs with Data Augmentation: (16.MLg_2c)

Now that you’ve seen Image Augmentation in action, it’s time to go back to the Cats v Dogs full Kaggle Challenge exercise. Last week you built a classifier for Cats v Dogs and trained it for a few epochs. This week I want you to add Augmentation to it, and experiment with different parameters to avoid overfitting. This will likely take a lot of time -- as it requires using the full dataset along with augmentation code to edit the data on-the-fly. The opportunity here is to try hard to get into State-of-the-Art type classification. Experiment with different images it hasn’t before seen, and see if you can get it to correctly classify them! For a particularly challenging image, see if you can get it to classify this one correctly:
https://pixabay.com/photos/bed-dog-animals-dogs-pets-relax-1284238/
--------------------------------------------------------------
Теперь, когда вы увидели увеличение изображения в действии, пришло время вернуться к полному упражнению Kaggle Challenge «Кошки против собак». На прошлой неделе вы создали классификатор для игры «Кошки против собак» и обучили его на несколько эпох. На этой неделе я хочу, чтобы вы добавили к нему аугментацию и поэкспериментировали с различными параметрами, чтобы избежать переобучения. Скорее всего, это займет много времени, поскольку для редактирования данных на лету требуется использование полного набора данных вместе с кодом дополнения. Возможность здесь состоит в том, чтобы изо всех сил стараться попасть в современную классификацию типов. Поэкспериментируйте с различными изображениями, которых он раньше не видел, и посмотрите, сможете ли вы заставить его правильно классифицировать их! Для особенно сложного изображения посмотрите, сможете ли вы правильно его классифицировать:
https://pixabay.com/photos/bed-dog-animals-dogs-pets-relax-1284238/
--------------------------------------------------------------
Lets now build the Cats vs. Dogs classifier using augmentation!
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/assignment/C2W2_Assignment.ipynb
--------------------------------------------------------------
Давайте теперь построим классификатор кошек против собак, используя аугментацию!
Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W2/assignment/C2W2_Assignment.ipynb
--------------------------------------------------------------
This notebook is hosted on github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
You should upload two files:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
create_train_val_dirs
split_data
train_val_generators
create_model
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
- The training history of your model (a file with .pkl extension) which will be used to grade the accuracy of your model.
--------------------------------------------------------------
Этот блокнот размещен на github, поэтому для сохранения любых изменений вам необходимо создать его копию на вашем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».
Вы должны загрузить два файла:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
create_train_val_dirs
split_data
train_val_generators
create_model
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.
- История обучения вашей модели (файл с расширением .pkl), которая будет использоваться для оценки точности вашей модели.

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
                                      
!_!
# file = "c2_week2_Passigment.ipynb"
Original cat's directory has 12500 images
Original dog's directory has 12500 images
There are 11249 images of cats for training
There are 11249 images of dogs for training
There are 1250 images of cats for validation
There are 1250 images of dogs for validation
train_generator = train_datagen.flow_from_directory(batch_size=_,),  Epoch 15/15
 accuracy;  | batch_size|1.Conv2D()|2.Conv2D()|3.Conv2D()|4.Conv2D()|5.Conv2D()|Dense()
val_accur   |  T   V    |          |          |          |          |          |          | 
-----------------------------------------------------------------------------------------------------------------
0,71; 0,75  |150   150  |  16      |   32     |  64      |   00     |   00     |  512    |
-----------------------------------------------------------------------------------------------------------------
0,64; 0,65  |020   020  |  16      |   32     |  64      |   64     |   00     |  512    |+st
-----------------------------------------------------------------------------------------------------------------
0,70; 0,66  |020   020  |  16      |   32     |  64      |   00     |   00     |  256    |+step(epoch, valid)
-----------------------------------------------------------------------------------------------------------------
0,67; 0,74  |128   032  |  16      |   32     |  64      |   64     |   00     |  256    |+st
-----------------------------------------------------------------------------------------------------------------
0,68; 0,66  |020   020  |  16      |   32     |  64      |   00     |   00     |  128    |+st
-----------------------------------------------------------------------------------------------------------------
0,66; 0,60  |020   020  |  16      |   32     |  00      |   00     |   00     |  128    |+st
-----------------------------------------------------------------------------------------------------------------
0,68; 0,70  |020   020  |  16      |   32     |  64      |   00     |   00     |  512    |+st
-----------------------------------------------------------------------------------------------------------------
0,69; 0,71  |040   040  |  16      |   32     |  64      |   00     |   00     |  512    |+st
-----------------------------------------------------------------------------------------------------------------
0,65; 0,69  |020   020  |    8      |   16     |  32      |   00     |   00     |  256    |+st
-----------------------------------------------------------------------------------------------------------------
   
              
<<<<<<< HEAD
=======
>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1
<<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD

NEXT week_3 (16.MLg_2c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3) Transfer Learning (16.MLg_2c)

(Трансферное обучение)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 13 minutes
Self-study: 45 min
Graded tasks (Tasks to be assessed): 2

(w3) Content (16.MLg_2c)

1. Transfer learning (dowload and take not own learned model)
2. Dropout layers
x = layers.Dropout(0.2)(x) (del 20% layers)
- Applying Transfer Learning to Cats v Dogs (Lab 1) (transfer and dropput)
- Programming Assignment: Transfer Learning - Horses vs Humans

(w3) Introduction: (16.MLg_2c)

Building models for yourself is great, and can be very powerful. But, as you've seen, you can be limited by the data you have on hand. Not everybody has access to massive datasets or the compute power that's needed to train them effectively. Transfer learning can help solve this -- where people with models trained on large datasets train them, so that you can either use them directly, or, you can use the features that they have learned and apply them to your scenario. This is Transfer learning, and you'll look into that this week!
---------------------------------------------------------------
Создание моделей для себя — это здорово, и это может быть очень эффективно. Но, как вы видели, вы можете быть ограничены имеющимися у вас данными. Не у всех есть доступ к массивным наборам данных или вычислительной мощности, необходимой для их эффективного обучения. Трансферное обучение может помочь решить эту проблему, когда люди с моделями, обученными на больших наборах данных, обучают их, чтобы вы могли либо использовать их напрямую, либо использовать изученные ими функции и применить их к своему сценарию. Это трансферное обучение, и вы изучите его на этой неделе!

(w3) Learning Objectives: (16.MLg_2c)

● Master the keras layer type known as dropout to avoid overfitting.
● Achieve transfer of learning to code using the keras API.
● Create a model that implements the functional Keras API instead of the widely used Sequential model.
● Learn how to freeze layers of an existing model to successfully implement transfer learning.
● Learn the concept of transfer learning to use convolutions learned by another model from a larger model.
data set
---------------------------------------------------------------
● Освойте тип слоя keras, известный как выпадение, чтобы избежать переобучения.
● Добейтесь переноса обучения в код с помощью keras API.
● Создайте модель, которая реализует функциональный API Keras вместо широко используемой модели Sequential.
● Узнайте, как заморозить слои существующей модели, чтобы успешно внедрить трансферное обучение.
● Изучите концепцию трансферного обучения, чтобы использовать свертки, изученные другой моделью из более крупной модели.
набор данных

1(w3)-video1: A conversation with Andrew Ng (16.MLg_2c)

Welcome back. Transfer learning is one of the most important techniques of deep learning and TensorFlow lets you do that with just a handful of lines of codes. Rather than needing to train a neural network from scratch we can need a lot of data and take a long time to train, you can instead download maybe an open-source model that someone else has already trained on a huge dataset maybe for weeks and use those parameters as a starting point to then train your model just a little bit more on perhaps a smaller dataset that you have for a given task, so it is called transfer learning. Transfer learning, and I find it's really cool because we've been looking at convolutional neural networks up to this point, and when we're training with a convolutional neural network we're extracting features from an image and learning those features, learning the ones that match images. But when we download a large models something like an inception that has all of these features that have already been extracted off lots more images than we can use, I find that really exciting because as you mentioned researchers who built these wonderful models of lots of images have been able to share them and today we've been looking at convolutions and convolutional neural networks where from scratch we've been training something off of our data and off of our images to be able to extract features from these and learn them. But now these models that have been trained off with lots and lots of images over a lot of time might have spotted other features that weren't in our dataset and will help us to build better convolutional networks. Yes. There's so much stuff for neural networks to learn about the world. There are edges, corners, round shapes, curvy shapes, blobs and then there are things like eyes, circles, squares, wheels. There's so many things in the world that convolutional neural networks can pick up on but if you have only a 1,000 images or even 25,000 images may not be enough data for content to learn all those things. So by taking an inception network or some other network that someone else's has trained you can basically download all this knowledge into your neural network to give it a huge and much faster start. It's really exciting to be a part of that community where these things are being shared so that people who don't have access to machinery to be able to build massive models like this one, are able to derive the features from the people who have done so. I personally find that really inspirational. Yes. Many days I wake up really grateful to the whole AI community for the openness, so many breakthrough AI ideas are shared in papers on the Internet, on the open source code shared on the Internet, and I think this has been a large reason for the rapid advance of AI. I think to all the learners if you end up doing something consider sharing it on the Internet as well freely to contribute back to this open community that's making all of us go much faster. Definitely. Transfer learning is a technical embodiment that lets us use these ideas to accelerate the whole field. One of the cool things about transfer learning is that it's so simple to implement, in TensorFlow you download a model and then you say set these models as trainable and freeze or lock those other layers and then you just run. Yes. In the course what the students are going to be looking at is the inception model which is a beautiful image classification and classifies a 1,000 images it has been trained on. I think it's like over a million images and what you're going to do is you're going to take a look at one of the lower levels in that. You're going to lock all the way down to that. You're going to add a DNN a deep neural network underneath that, and then you're just going to retrain for those lower levels, and as a result using all of these, I like to call it standing on the shoulders of giants, you're going to be doing all that to be able to make the classifiers that you've been building in the course to date much more efficient and maybe even quicker to be able to reach higher levels of accuracy than if you're training it from scratch. So this week, you'll learn how to implement transfer learning and use it to get your models to not only train faster but also get higher accuracy. Please dive in.
---------------------------------------------------------------
С возвращением! Перенос обучения — это одна из самых важных методик глубокого обучения, и TensorFlow позволяет вам организовывать её всего в несколько строк кода. Вместо того, чтобы тренировать нейросеть с нуля, нуждаясь в большом количестве данных и времени на тренировку, — вы можете скачать модель, возможно, с открытым кодом, которую кто-то уже тренировал на огромном наборе данных, возможно, в течение нескольких недель, — и использовать её параметры как отправную точку, с которой начать тренировать вашу модель, лишь чуть-чуть, и, возможно, на меньшем наборе данных, который вы собрали для вашей задачи. Вот это и называется переносом обучения. Перенос обучения — и я считаю, это действительно круто, потому что мы до сих пор смотрели на свёрточные нейросети, и когда мы тренировали свёрточные нейросети, мы извлекали признаки из изображений, и обучали на эти признаки, изучали те из них, которые определяют изображения. Но когда мы загружаем большие модели такие, как Inception, то у них уже есть все эти признаки, которые уже извлечены из куда большего количества изображений, чем мы можем использовать, и я нахожу это поистине впечатляющим, потому что, как вы упомянули, исследователи, которые строят эти чудесные модели на большом количестве изображений, могут делиться ими, и теперь мы смотрим на эти свёртки и свёрточные нейросети, которые с нуля мы не смогли бы натренировать с нашими данными и нашими изображениями так, чтобы суметь при этом извлечь из них признаки, узнать их. Но сейчас эти модели, которые были натренированы на очень большом количестве изображений в течение огромного количества времени, — способны улавливать другие признаки, которых не было в нашем наборе данных, и они помогут нам построить лучшую свёрточную сеть. Да. Есть так много всего, что нейросети должны узнать об окружающем мире. Есть края, углы, круглые формы, изогнутые формы, пятна, а ещё есть такие вещи, как глаза, круги, квадраты, колёса. В мире столько всего, что свёрточные сети могли бы выучить, но если у вас есть только тысяча изображений, или даже 25 тысяч изображений, то может быть недостаточно данных для того, чтобы всему этому научиться. И взяв сеть Inception, или какую-нибудь другую сеть, которую натренировал кто-то другой, вы можете фактически загрузить все эти знания в вашу нейросеть, чтобы дать ей мощный и куда более быстрый старт. Я действительно впечатлён тем, что являюсь частью этого сообщества, в котором делятся такими вещами, так что люди, у которых нет доступа к суперкомпьютерам, чтобы построить такие колоссальные модели, как эта, теперь способны позаимствовать признаки у тех, кто это уже сделал. Лично я считаю это очень вдохновляющим. Да, много дней я просыпаюсь по-настоящему благодарным всему сообществу, изучающему ИИ, за его открытость, ведь так много прорывных идей в области ИИ распространялись в статьях в Интернете, в открытом коде, выложенном в Интернете, и я думаю, это послужило существенной причиной быстрого развития ИИ. И я думаю, что все наши ученики, если они в итоге сделают что-то важное, подумают о том, чтобы тоже выложить это в свободный доступ в Интернет, чтобы вернуть долг этому открытому сообществу, которое даёт всем нам возможность быстрее развиваться. Несомненно. Перенос обучения — это техническое воплощение, которое позволяет нам использовать эти идеи, чтобы ускорить развитие целой области знаний. Одна из замечательных вещей в переносе обучения – это то, что его очень просто внедрить, в TensorFlow вы просто скачиваете модель, а потом указываете в коде, что эту модель можно тренировать, и замораживаете некоторые слои, и затем просто запускаете на выполнение. Да, и в этом курсе, который студенты сейчас смотрят, есть модель Inception, прекрасный классификатор изображений, и она классифицирует тысячу изображений, тогда как натренирована была, полагаю, на более чем миллионе изображений, и вам предстоит сделать вот что: взглянуть в ней на один из самых нижних уровней. Вы заморозите всё, что до него. Вы добавите ГНС, глубокую нейросеть, под этим слоем, а затем вы просто ещё немного потренируете эти нижние уровни, и в результате используете это всё, мне нравится называть это "стоять на плечах гигантов", вы сделаете это всё, чтобы сделать классификатор, созданием которого вы уже занимались при прохождении этого курса, — намного более эффективным, и, возможно, ещё быстрее достичь высших уровней точности, чем если бы вы тренировали его с нуля. Итак, на этой неделе вы научитесь внедрять перенос обучения и использовать его, чтобы ваша модель не только быстрее обучалась, но и давала более высокую точность. Пожалуйста, погружайтесь в курс.

2(w3)-video2: Understanding transfer learning: the concepts (16.MLg_2c)

In the previous lessons, you looked at building a binary classifier that predicted cats versus dogs or horses versus humans. You also saw how overfitting can occur and explored some practices for avoiding it. The problem with these of course, is that the training data was very small, and there's only so many common features that can be extracted, even if we do some tricks like image augmentation. But in both these cases, you built the model from scratch. What if you could take an existing model that's trained on far more data, and use the features that that model learned? That's the concept of transfer learning, and we'll explore that in this lesson. So for example, if you visualize your model like this with a series of convolutional layers before dense layer leads your output layer, you feed your data into the top layer, the network learns the convolutions that identify the features in your data and all that. But consider somebody else's model, perhaps one that's far more sophisticated than yours, trained on a lot more data. They have convolutional layers and they're here intact with features that have already been learned. So you can lock them instead of retraining them on your data, and have those just extract the features from your data using the convolutions that they've already learned. Then you can take a model that has been trained on a very large datasets and use the convolutions that it learned when classifying its data. If you recall how convolutions are created and used to identify particular features, and the journey of a feature through the network, it makes sense to just use those, and then retrain the dense layers from that model with your data. Of course, well, it's typical that you might lock all the convolutions. You don't have to. You can choose to retrain some of the lower ones too because they may be too specialized for the images at hand. It takes some trial and error to discover the right combination. So let's take a well-trained state of the art model. There's one called Inception, which you can learn more about at his site. This has been pre-trained on a dataset from ImageNet, which has 1.4 million images in a 1000 different classes.
---------------------------------------------------------------
На предыдущих занятиях вы наблюдали за построением бинарного классификатора, определяющего что на изображении: кошка или собака, лошадь или человек. Вы также видели, как может возникать переобучение, и изучили некоторые методы противодействия ему. Основная проблема, конечно, была в очень малом размере тренировочного набора, и при этом так много общих признаков можно извлечь, даже если мы используем ряд приёмов, например, аугментацию. Но в обоих этих случаях вы строили модель с нуля. Что, если бы вы могли взять существующую модель, натренированную на намного большем количестве данных, — и использовать признаки, которым эта модель научилась? В этом ключевая идея переноса обучения, и мы рассмотрим его на этом уроке. Например, если вы изобразите свою модель, как здесь, с набором свёрточных слоёв, предшествующих полносвязному слою, который ведёт в выходной слой, где вы подаёте данные в верхний слой, и сеть обучает свёртки, которые находят признаки в ваших данных. Но посмотрите на чужую модель, возможно, намного более сложную, чем ваша, натренированную на намного большем количестве данных. У неё есть свёрточные слои, и они здесь определяют признаки, которые уже выучены. Так что вы можете заморозить их, вместо того, чтобы дообучать ещё и на ваших данных, — и использовать их только для извлечения признаков из ваших данных, используя свёртки, которые уже обучены. Тогда вы можете взять модель, которая натренирована на очень большом наборе данных, и использовать свёртки, которые она обучила, когда классифицировала эти данные. Если вы вспомните, как свёртки создаются и используются для извлечения признаков, и о том, как признаки передаются по сети, — то поймёте, что имеет смысл просто использовать их, и дообучать только плотные слои этой модели на ваших данных. Конечно, это только распространённый вариант — замораживать все свёртки, но вы вовсе не обязаны это делать. Вы можете решить дообучить также некоторые из нижних свёрток, потому что они могут быть слишком специфичны для применения на ваших изображениях. Потребуется ряд проб и ошибок, чтобы найти подходящий вариант. Итак, давайте возьмём качественно обученную современную модель. Например, вот эту, которая называется Inception, и о которой вы можете больше узнать на её сайте. Она уже натренирована на наборе данных ImageNet, в котором 1.4 миллиона изображений, разделённых на 1000 классов.

3(w3)-video3: Coding transfer learning from the inception model (16.MLg_2c)

So let's take a look at how we would achieve this in code. We'll start with the inputs. In particular, we'll be using the keras layers API, to pick at the layers, and to understand which ones we want to use, and which ones we want to retrain. A copy of the pretrained weights for the inception neural network is saved at this URL. Think of this as a snapshot of the model after being trained. It's the parameters that can then get loaded into the skeleton of the model, to turn it back into a trained model. So now if we want to use inception, it's fortunate that keras has the model definition built in. So you instantiate that with the desired input shape for your data, and specify that you don't want to use the built-in weights, but the snapshot that you've just downloaded. The inception V3 has a fully-connected layer at the top. So by setting include_top to false, you're specifying that you want to ignore this and get straight to the convolutions. Now that I have my pretrained model instantiated, I can iterate through its layers and lock them, saying that they're not going to be trainable with this code. You can then print a summary of your pretrained model with this code but be prepared, it's huge. There's no way I can fit it all in a slide, even if I use a two point font like this. This is probably less than 10 percent of the summary of the model. Try it in the notebook for yourself.
---------------------------------------------------------------
Итак, давайте посмотрим, как написать для этого код. Мы начнём с импорта библиотек. В частности, мы будем использовать интерфейс слоёв keras, чтобы выбирать слои, и понимать, какие мы хотим использовать, как они есть, а какие мы хотим дообучать. Копия предварительно натренированных весов для нейросети Inception хранится по этой ссылке. Считайте это моментальным снимком модели после того, как она была обучена. Это параметры, которые можно загрузить в скелет модели, чтобы превратить её в натренированную модель. Итак, если мы хотим использовать Inception, то, к счастью, в Keras есть встроенное определение этой модели. Так что вы создаёте экземпляр сети, задав желаемую форму для ваших данных, и указав, что вам нужны не встроенные веса, а снимок, который вы только что скачали. В Inception V3 на самом верху есть полносвязный слой, так что, установив параметр include_top=False, вы указываете, что хотите его игнорировать, и переходить прямо к свёрткам. И теперь, когда я создал свой экземпляр предварительно натренированной модели, я могу пройтись по всем слоям, и заморозить их, имея в виду, что не собираюсь тренировать их в этом коде. Затем вы можете вывести сводку об этой модели с помощью данного кода, но будьте готовы: она огромная. Я никак не могу уместить это в один слайд,так даже если буду использовать шрифт размером в 2 пункта, как здесь. И это, вероятно, менее 10% сводки об этой модели. Попробуйте это в блокноте самостоятельно.

4(w3)-Adding your DNN: (16.MLg_2c)

In the previous video you saw how to take the layers from an existing model, and make them so that they don't get retrained -- i.e. you freeze (or lock) the already learned convolutions into your model. Now, you'll need to add your own DNN at the bottom of these, which you can retrain to your data. In the next video, you'll see how to do that...
---------------------------------------------------------------
В предыдущем видео вы видели, как взять слои из существующей модели и сделать их такими, чтобы они не подвергались переобучению — то есть вы заморозили (или заблокировали) уже изученные свертки в своей модели. Теперь вам нужно добавить свой собственный DNN внизу, который вы можете переобучить своим данным. В следующем видео вы увидите, как это сделать...

5(w3)-video4: Coding your own model with transferred features (16.MLg_2c)

All of the layers have names, so you can look up the name of the last layer that you want to use. If you inspect the summary, you'll see that the bottom layers have convolved to 3 by 3. But I want to use something with a little more information. So I moved up the model description to find mixed7, which is the output of a lot of convolution that are 7 by 7. You don't have to use this layer and is fun to experiment with others. But with this code, I'm going to grab that layer from inception and take it to output.
So now we'll define our new model, taking the output from the inception model's mixed7 layer, which we had called last_ouput. This should look exactly like the dense models that you created way back at the start of this course. The code is a little different, but this is just a different way of using the layers API. You start by flattening the input, which just happens to be the output from inception. And then add a Dense hidden layer. And then your output layer which has just one neuron activated by a sigmoid to classify between two items. You can then create a model using the Model abstract class. And passing at the input and the layers definition that you've just created.
And then you compile it as before with an optimizer and a loss function and the metrics that you want to collect. I won't go into all the codes to download cats versus dogs again, it's in the workbook if you want to use it. But as before you're going to augment the images with the image generator. Then, as before, we can get our training data from the generator by flowing from the specified directory and going through all the augmentations. And now we can train as before with model.fit_generator. I'm going to run it for 100 epochs. What's interesting if you do this, is that you end up with another but a different overfitting situation. Here is the graph of the accuracy of training versus validation. As you can see, while it started out well, the validation is diverging away from the training in a really bad way. So, how do we fix this? We'll take a look at that in the next lesson.
---------------------------------------------------------------
У всех слоёв есть названия, так что вы можете посмотреть на название последнего слоя, который вы хотите использовать. Если вы изучите сводку о модели, то увидите, что нижний слой сворачивается до размера 3x3. Но я хочу использовать слой с бо́льшим количеством информации, так что я пролистал описание модели, чтобы найти слой с названием mixed7, который является выходом множества свёрток размером 7x7. Вы не обязаны использовать именно этот слой, и было бы забавно поэкспериментировать с другими. Но в этом коде я собираюсь взять именно этот слой модели Inception, и использовать его выход.
А теперь зададим новую модель, взяв вывод из слоя mixed7 модели Inception, который мы назвали last_output. Это должно выглядеть в точности как полносвязная модель, которую вы создали давным-давно, в начале этого курса. Код немного другой, но это просто другой способ использования API слоёв. Вы начинаете с того, что делаете одномерным вход, которым нам служит вывод из Inception. А затем добавляете полносвязный скрытый слой. А за ним — выходной слой, в котором есть лишь один нейрон, активируемый сигмоидой, для классификации на два класса. Затем вы создаёте модель, используя абстрактный класс Model, и передаёте ей вход и определение слоёв, которые вы только что создали.
Затем вы скомпилируете её, как и раньше, задав оптимизатор и функцию потерь, а также метрики, которые вы хотите собирать. Я не буду углубляться в весь код, который снова загружает "кошки или собаки", он есть в блокноте, если вам надо. Но, как и раньше, вам нужна аугментация с помощью генератора изображений. Затем, как и раньше, мы получим наши тренировочные данные из генератора, читая их из указанной папки и пропуская через все аугментации. А теперь, как и прежде, натренируем модель, использовав model.fit_generator. Я собираюсь тренировать её 100 эпох. Интересно, что если вы так сделаете, то снова окажетесь в ситуации переобучения, только уже другой. Вот график верных ответов на обучении и валидации. Вы видите, что всё начиналось хорошо, а затем валидация очень далеко ушла от обучения. Как мы можем это исправить? Мы узнаем это в следующем уроке.

6(w3)-Using dropout!: (16.MLg_2c)

Another useful tool to explore at this point is the Dropout.
The idea behind it is to remove a random number of neurons in your neural network. This works very well for two reasons: The first is that neighboring neurons often end up with similar weights, which can lead to overfitting, so dropping some out at random can remove this. The second is that often a neuron can over-weigh the input from a neuron in the previous layer, and can over specialize as a result. Thus, dropping out can break the neural network out of this potential bad habit!
Check out Andrew's terrific video explaining dropouts here:
https://www.youtube.com/watch?v=ARq74QuavAo
---------------------------------------------------------------
Еще один полезный инструмент для изучения на этом этапе — Dropout.
Идея заключается в том, чтобы удалить случайное количество нейронов в вашей нейронной сети. Это очень хорошо работает по двум причинам: во-первых, соседние нейроны часто имеют одинаковые веса, что может привести к переоснащению, поэтому случайное отбрасывание некоторых нейронов может устранить это. Во-вторых, часто нейрон может перевешивать входные данные от нейрона предыдущего слоя и в результате может чрезмерно специализироваться. Таким образом, отсев может сломать нейронную сеть от этой потенциально вредной привычки!
Посмотрите потрясающее видео Эндрю, объясняющее отсев, здесь:
https://www.youtube.com/watch?v=ARq74QuavAo

7(w3)-video5: Exploring dropouts (16.MLg_2c)

In the previous lesson, we saw how to do transfer learning. But when we retrain the inception classifier features for cats versus dogs, we ended up over-fitting again. We also had augmentation, but despite that, we still suffered from over-fitting. So let's discuss some ways that we can avoid that in this lesson. Now here's the accuracy of our training set versus our validation set over 100 epochs. It's not very healthy.
There's another layer take in Keras called a dropout. And the idea behind the dropout is that layers in a neural network can sometimes end up having similar weights and possible impact each other leading to over-fitting. With a big complex model like this, that's a risk. So if you can imagine the dense layers can look a little bit like this. By dropping some out, we make it look like this. And that has the effect of neighbors not affecting each other too much and potentially removing overfitting. So how do we achieve this in code? Well, here's our model definition from earlier. And here's where we add the dropout. The parameter is between 0 and 1 and it's the fraction of units to drop. In this case, we're dropping out 20% of our neurons. For comparison, here's the chart of training against accuracy from before the dropout was added. When you see validation diverging away from the training like this over time, it's actually a great candidate to try using a dropout. And here's the impact of the dropout. You can see that it's very significant. So lets take a look at this in the workbook.
---------------------------------------------------------------
В предыдущем уроке мы увидели, как делать перенос обучения. Но когда мы дообучали классификатор из Inception для "кошек или собак", мы опять пришли к переобучению. У нас была и аугментация, но несмотря на это, мы всё ещё страдаем от переобучения. Давайте в этом уроке обсудим несколько способов избавиться от него. Вот доля верных ответов на тренировочном и валидационном наборах данных на протяжении 100 эпох. Она не слишком хорошая.
В Keras есть ещё один слой, называемый слоем исключения/дропаута. И замысел, на котором он основан, состоит в том, что иногда слои в нейросетях могут иметь похожие веса и влиять друг на друга, что приводит к переобучению. В таких больших и сложных моделях, как эта, такое возможно. И если представить полносвязные слои, выглядящие примерно так, то частичным исключением мы можем привести их к такому виду. Это приводит к тому, что соседи влияют друг на друга не слишком сильно, что может устранить переобучение. Как же мы добьёмся этого в коде? Вот как мы определили модель ранее. И вот как мы добавляем дропаут. Параметр должен быть между 0 и 1, это доля элементов, которые надо отбросить. Здесь мы отбрасываем 20% наших нейронов. Для сравнения, вот график тренировочной и валидационной доли верных ответов до того, как мы добавили дропаут. Когда вы видите, что доля верных ответов на валидации со временем далеко уходит от тренировочной — значит, пора попробовать дропаут. И вот эффект от дропаута. Вы можете видеть, что он очень существенный. Давайте посмотрим всё это в блокноте.

8(w3)-Applying Transfer Learning to Cats v Dogs (Lab 1): (16.MLg_2c)

Now that we've explored transfer learning, and taken a look at regularization using dropout, let's step through the scenario for Cats vs Dogs in this
notebook next.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/ungraded_lab/C2_W3_Lab_1_transfer_learning.ipynb
For more on how to freeze/lock layers, you can explore the
documentation here.
https://www.tensorflow.org/tutorials/images/transfer_learning
---------------------------------------------------------------
Применение трансферного обучения к игре «Кошки против собак» (лабораторная работа 1)
Теперь, когда мы изучили переносное обучение и взглянули на регуляризацию с помощью отсева, давайте рассмотрим сценарий «Кошки против собак» в этом
тетрадь рядом.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/ungraded_lab/C2_W3_Lab_1_transfer_learning.ipynb
Чтобы узнать больше о том, как заморозить/заблокировать слои, вы можете изучить
документация здесь.
https://www.tensorflow.org/tutorials/images/transfer_learning

9(w3)-video6: Exploring Transfer Learning with Inception (16.MLg_2c)

Here's the transfer learning workbook from this lesson. Let's step through it, and when we're done, you can try it for yourself. The first cell downloads the weights for a pre-trained inception network, and then instantiates a new instance of it using those weights. We will pull one of the convolutional layers as our input layer, and then take its output. We call this last output. Now, we'll set up our model taking the last output as the input to it. That'll be flattened, and then there'll be a dense layer, a dropout, and an output layer. The next cell will download the abbreviated version of cats versus dogs, unzip it into training and validation directories, and then set up the image generators. The training one will use augmentation as we've explored before. We can then see that the images are being loaded and segregated into classes correctly, 2,000 for training, 1,000 for validation. We'll now start the training. I'm only going to do 20 epochs. Keep an eye on the accuracy and validation accuracy metrics. I'm speeding up the video to save a little time. But as you can see, the training accuracy is steadily increasing, and the validation accuracy is settling in about the mid 90's. By the time we're done, the training accuracy is around 90 percent, and the validation is close to 97 percent. That's in pretty good shape. So let's plot the 20 epochs and we can see that the curves are in sync. This is a good sign that we're avoiding overfitting. So that's it for this lesson. In this and in the last few lessons, we spent a lot of time looking at convolutional neural networks for classifying binary values. Of course another scenario happens when you have to classify multiple objects. So in the next lesson, we'll look at what you have to do to achieve that.
---------------------------------------------------------------
Вот блокнот данного урока по переносу обучения. Давайте пройдёмся по нему, и когда мы закончим, вы сможете попробовать всё сами. Первая ячейка скачивает веса для предобученной сети Inception, а затем создаёт новый экземпляр сети, используя эти веса. Мы указываем на один из свёрточных слоёв как на наш входной слой, а затем берём его вывод. Мы называем его last_output. Теперь настраиваем нашу модель, взяв last_output в качестве входа для неё. Его надо сделать плоским, а затем добавить полносвязный слой, дропаут и выходной слой. Следующая ячейка скачает сокращённую версию набора "кошка или собака", распакует его в тренировочную и валидационную папки, и затем настроит генераторы изображений. Тренировочный генератор будет использовать аугментацию, как мы уже посмотрели. Мы видим, что изображения загружаются и делятся на классы правильно. 2000 на тренировку, 1000 на валидацию. Теперь начнём тренировку. Я запускаю её лишь на 20 эпох. Следите за тренировочной и валидационной долей верных ответов. Я ускоряю видео, чтобы сэкономить немного времени. Но как вы видите, тренировочная доля верных ответов постоянно увеличивается, а валидационная — колеблется около 95%. К тому времени, как мы закончим, тренировочная доля верных ответов будет около 90%, а валидационная — близка к 97%. Это довольно хорошо. Давайте выведем график за 20 эпох, и увидим, что кривые синхронны. Это хороший признак того, что мы преодолели переобучение. Вот и всё на этот раз. В этом и нескольких предыдущих уроках мы потратили много времени, рассматривая свёрточные нейросети для бинарной классификации. Конечно, вы встретитесь с другими особенностями, когда будете классифицировать на несколько классов. И в следующем уроке мы посмотрим, что вам для этого нужно сделать.

10(w3)-What have we seen so far?: (16.MLg_2c)

This week you've learned a lot of great new concepts!
You saw Transfer Learning, and how you can take an existing model, freeze many of its layers to prevent them being retrained, and effectively 'remember' the convolutions it was trained on to fit images.
You then added your own DNN underneath this so that you could retrain on your images using the convolutions from the other model.
You learned about regularization using dropout to make your network more efficient in preventing over-specialization and thus overfitting.
Before you get to the exercise for this week, let's have a quick quiz!
---------------------------------------------------------------
На этой неделе вы узнали много новых отличных концепций!
Вы видели Transfer Learning и то, как вы можете взять существующую модель, заморозить многие из ее слоев, чтобы предотвратить их переобучение, и эффективно «запомнить» свертки, на которых она была обучена, чтобы соответствовать изображениям.
Затем вы добавили свою собственную DNN под этим, чтобы вы могли переобучить свои изображения, используя свертки из другой модели.
Вы узнали о регуляризации с помощью отсева, чтобы сделать вашу сеть более эффективной в предотвращении чрезмерной специализации и, следовательно, переобучения.
Прежде чем вы приступите к упражнению на этой неделе, давайте проведем небольшую викторину!

11(w3)- Week 3 Quiz: (16.MLg_2c)

1)If I put a dropout parameter of 0.2, how many nodes will I lose?:
1. 20% of them (+)
2. 2% of them
3. 20% of untrained ones
4. 2% of untrained ones
2) Why is transfer learning useful?:
1. Because I can use all of the data from the original training set
2. Because I can use all of the data from the original validation set
3. Because I can use the features that were learned from large datasets that I may not have access to(+ -)
4. Because I can use the validation metadata from large datasets that I may not have access to
3) How did you lock or freeze a layer from retrainig?:
1. tf.freeze(layer)
2. tf.layer.frozen = true
3. tf.layer.locket =true
4. layer.trainable = false (+)
4) How do you change the number of classes the model can classify when using transfer learning?(i.e. the original model handled 1000 classes, but yours handles just 2):
1. Ignore all the classes above yours (i.e. Numbers 2 onwards if I'm just classing2)
2. Use all classes but set their weights to 0
3. When you add your DNN at the bottom of the network, you specify your output layer with the number of classes you want(+)
4. Use dropouts to eliminate the unwanted classes
5) Can you use Image Augmentation with Transfer Learning Models?:
1. No, because you are using pre-set features
2. Yes, because you are adding new layers at the bottom of the network, and you can use image augmentation when training these(+)
6) Why do dropouts help avoid overfitting?:
1. Because neighbor neurons can have similar weights, and this can skew the final training(+)
2. Having less neurons speeds up training
7) What would the symptom of a Dropout rate being set too nigh?:
1. The network would lose specialization to the effect that it would be inefficient of ineffective at learning, driving accuracy down (+)
2. Training time would increase due to the extra calculations being required for higher dropout
8) Which is the correct line of code for adding Dropout of 20% of neurons using TensorFlow:
1. tf.keras.layers.Dropout(20)
2. tf.keras.layers.DropoutNeuros(20)
3. tf.keras.layers.Dropout(0.2) (+)
4. tf.keras.layers.DropoutNeuros(0.2)

12(w3)-video7: Week 3 Wrap up (16.MLg_2c)

Congratulations, you've reached the end of week three. This week, hopefully you're excited as I was by some of the things that you learned. When you looked at Transfer Learning, just realize some of the things that were there, that were available for you, that you were able to take somebody else's model, a massive model that took a long time with a lot of data to train from, but you were able to build on that to make your models even better. I personally find that something that's really inspiring and something that really excites me. But next week we're going to switch gears a little bit, and we're going to take a look at moving from your binary classification to multi class classification to just round out your toolbox. I'll see you there.
---------------------------------------------------------------
Поздравляю, вы достигли конца третьей недели. На этой неделе, надеюсь, вы, как и я, восхитились тому, что узнали. Когда вы смотрели на перенос обучения, то одно только понимание того, что в него входит, что оно вам доступно, и можно взять чьи-то чужие модели, огромные модели, которые нужно было тренировать много времени на большом количестве данных, — но вы смогли положиться на них, чтобы сделать ваши модели ещё лучше. Лично я считаю это очень вдохновляющим и восхитительным. Но на следующей неделе мы собираемся немного переключиться, и посмотрим, как перейти от вашей бинарной классификации — к мультиклассовой, чтобы пополнить ваш инструментарий. Увидимся.

13(w3)-Lecture Notes Week 3: (16.MLg_2c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice These slides are distributed under the Creative Commons License.DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
ou may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах Эти слайды распространяются по лицензии Creative Commons. DeepLearning.AI делает эти слайды доступными для образовательных целей.
https://www.deeplearning.ai
Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

14(w3)-Programming Assignment: Transfer Learning - Horses vs Humans: (16.MLg_2c)

This week your exercise will be to apply what you've learned about Transfer Learning to see if you can increase training accuracy for Horses v Humans. To avoid crazy overfitting, your validation set accuracy should be around 95% if you do it right!
Your training should automatically stop once it reaches this desired accuracy.
Let's now use Transfer Learning to increase the training accuracy for Horses v Humans!
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/assignment/C2W3_Assignment.ipynb
This notebook is hosted on github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
You should upload one file:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
train_val_generators
create_pre_trained_model
output_of_last_layer
create_final_model
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
На этой неделе вам предстоит применить то, что вы узнали о трансферном обучении, чтобы увидеть, сможете ли вы повысить точность обучения в игре «Лошади против людей». Чтобы избежать сумасшедшего переоснащения, точность вашего набора проверки должна быть около 95%, если вы все сделаете правильно!
Ваша тренировка должна автоматически остановиться, как только она достигнет желаемой точности.
Теперь давайте воспользуемся трансферным обучением, чтобы повысить точность обучения в игре «Лошади против людей»!
Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/assignment/C2W3_Assignment.ipynb
Этот блокнот размещен на github, поэтому для сохранения любых изменений вам необходимо создать его копию на вашем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».
Вы должны загрузить один файл:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
train_val_generators
create_pre_trained_model
output_of_last_layer
create_final_model
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

NEXT week_4 (16.MLg_2c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w4) Multiclass Classifications (16.MLg_2c)

(Мультиклассовые классификации)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 11 minutes
Self-study: 46 min
Graded tasks (Tasks to be assessed): 2

(w4) Content (16.MLg_2c)

1. Moving from binary to multi-class classification
2. Introducing the Rock-Paper-Scissors dataset
3. Train a classifier with Rock Paper Scissors
4. Test the Rock Paper Scissors classifier
- Check out the code! (Lab 1)

(w4) Introduction: (16.MLg_2c)

You've come a long way, Congratulations! One more thing to do before we move off of ConvNets to the next module, and that's to go beyond binary classification. Each of the examples you've done so far involved classifying one thing or another -- horse or human, cat or dog. When moving beyond binary into Categorical classification there are some coding considerations you need to take into account. You'll look at them this week!
---------------------------------------------------------------
Вы прошли долгий путь, поздравляю! Еще одна вещь, которую нужно сделать, прежде чем мы перейдем от ConvNets к следующему модулю, и это выйти за рамки бинарной классификации. Каждый из приведенных вами примеров включал классификацию того или иного объекта — лошадь или человек, кошка или собака. При переходе от бинарной к категориальной классификации необходимо учитывать некоторые аспекты кодирования. Вы посмотрите на них на этой неделе!

(w4) Learning Objectives: (16.MLg_2c)

● Build a multiclass classifier for the Sign Language MNIST dataset
● Learn how to properly set up the ImageDataGenerator parameters and the model definition functions for multiclass classification
● Understand the difference between using actual image files vs images encoded in other formats and how this changes the methods available when using ImageDataGenerator
● Code a helper function to parse a raw CSV file which contains the information of the pixel values for the images used
---------------------------------------------------------------
● Создайте многоклассовый классификатор для набора данных MNIST языка жестов.
● Узнайте, как правильно настроить параметры ImageDataGenerator и функции определения модели для многоклассовой классификации.
● Понимать разницу между использованием реальных файлов изображений и изображений, закодированных в других форматах, и понимать, как это меняет методы, доступные при использовании ImageDataGenerator.
● Создайте вспомогательную функцию для анализа необработанного CSV-файла, который содержит информацию о значениях пикселей для используемых изображений.

1(w4)-video1: A conversation with Andrew Ng (16.MLg_2c)

The last few you train horse versus humans, cats versus dogs, would bind the classification problems with just two output. For a lot of applications, you might want more than two output courses such as Rock Paper Scissors where you would have three possible courses. So in this week, you learn the details of how to implement this. And in fact, you've actually seen one version of this already in the first course where you did the ten course classification problem of fashion. But in this week, you'll learn the important coding difference of how to actually build these multi-class classifiers. >> Yes, exactly, and it's one of the things that's really exciting about the image data generator is how your images get automatically labeled based on the directories that they're in. So we'll take a look at having with rock, paper, scissors, for example, we'll have three sub-directories of rock, paper, and scissors with the images in them. And we'll learn how the image data generator then works in outside of binary mode and in multi-class mode. We'll also look at the coding changes that you would have within the DNN part of your convolutional neural network so that you can work more efficiently with multi-class. >> And one of the really cool things we'll see this week is the rock, paper, scissors data set that you generated using computer graphics. >> Yeah, so I wanted to explore that one of the bottlenecks I find in creating data sets is in getting access to data. And if I wanted to build a rock, paper, scissors, I wanted to have people of different races hands. So Asian hands, black hands, white hands. I wanted to have male and female hands. I wanted to have nail polish and pointy nails on some and I wanted to have big hands and little hands. And if I were to do that with real images, I'd have to hire a lot of models and I didn't have the budget for that. And so, I thought well, what if I do it with CGI? And if I generate CGI hands for all of these, and then to see. Because convolutions are really all about extracting features. What does a finger look like? What does a finger nail look like? That type of thing. And with photo real CGI, the convolutions that make for finger might look exactly the same that it would be of a photograph of a hand. So I wanted to explore that and do some training on that. And it works surprisingly well. >> Yeah, one of the exciting developments in deep learning is that computer graphics is advanced to the point where more and more groups are considering using computer graphics to generate images to feed to these incredibly data hungry deep learning algorithms. Several years ago, when computer graphics was less advanced, it was like a slightly fishy thing to do to use computer graphics to synthesize data. And even though today, using graphics, not a slam dunk, it does not always work, and there's still problems quite often. I thought it was really cool that you were able to generate a pretty decent data set, certainly good enough for a learning tool. And in other context, I see companies starting to explore these ideas for more and more settings as well. >> Yeah, I think as an industry, we're only getting started with it. And that's really, really good for us to experiment with these things. And hopefully, the students in this course being able to experiment using these CGI based data sets will be a nice introduction for them. >> Yeah, so more data to feed to this giant hungry maw of our data hungry deep learning algorithms. >> Exactly. >> So in this week, you get to play with this cool new data set and use it to practice implementing building multi-class classifiers in TensorFlow. Please dive in.
---------------------------------------------------------------
Ваши последние модели — "лошадь или человек", "кошка или собака" — ограничивались только двумя вариантами ответа. Для многих других задач вам, вероятно, понадобится более двух вариантов, например, три варианта в игре "камень-ножницы-бумага". И на этой неделе вы подробно изучите, как это сделать. Фактически, вы уже видели один вариант, в первом курсе, где вы делали классификацию набора с изображениями одежды по 10 классам. Но на этой неделе вы научитесь важной отличительной черте в кодировании того, как на самом строятся многоклассовые классификаторы. >> Да, точно. И одна из вещей, которая действительно восхищает в генераторах изображений, это то, что ваши изображения размечаются автоматически, в зависимости от того, в какой папке лежат. Давайте для примера посмотрим, что у нас получится с "камень-ножницы-бумага", у нас будут три подкаталога: для камня, ножниц и бумаги, с изображениями в них. И мы узнаем, как работает генератор изображений в режиме мультиклассовой, а не бинарной классификации. Мы также посмотрим на то, как меняется код в части, относящейся к устройству вашей свёрточной нейросети, чтобы можно было эффективнее работать с несколькими классами. И одна из действительно крутых вещей, которые мы увидим на этой неделе, — набор данных "камень-ножницы-бумага", который вы сгенерировали с помощью компьютерной графики. Да, я хотел изучить одно из узких мест, на которое наткнулся: получение доступа к данным. Если я хочу построить набор данных для "камень-ножницы-бумага", то мне нужны руки людей разных рас. Азиатские руки, чёрные руки, белые руки. Мне нужны мужские и женские руки. Мне нужны руки с маникюром, и несколько рук с длинными ногтями. Мне нужны большие руки и маленькие. И если бы я захотел работать на настоящих изображениях, мне пришлось бы нанять множество моделей. Но у меня не было на это денег. И, я подумал: а что, если я сделаю это при помощи компьютерной графики? И сгенерирую на компьютере руки со всеми этими параметрами, а там посмотрим? Потому что свёртки ведь извлекают все эти признаки: Как выглядят пальцы? Как выглядят ногти на пальцах? И тому подобные вещи. И с фотореалистичной графикой свёртка, тренируемая на поиск пальцев, должна выглядеть точно так же, как если бы это были фотографии рук. Итак, я захотел исследовать это, и пообучал на данном наборе. И это сработало на удивление хорошо. Да, одно из потрясающих событий в глубоком обучении — что компьютерная графика продвинулась настолько, что всё больше и больше групп рассматривает возможность её применения для генерации изображений, чтобы подавать их на вход всем этим невероятно голодным до данных алгоритмам глубокого обучения. Несколько лет назад, когда компьютерная графика была не такая развитая, использовать её для синтеза данных казалось несколько сомнительным делом. И даже сегодня её использование не гарантирует успеха, она не всегда работает, всё ещё часто бывают трудности. По-моему, это действительно круто, что вы смогли сгенерировать вполне пристойный набор данных, который явно достаточно хорош для обучения. И в другом контексте, я вижу, как компании всё больше используют эти идеи, применяя их всё шире и шире. Да, я думаю, индустрия только начала с этим разбираться. И для нас очень, очень полезно экспериментировать с такими вещами. И я надеюсь, студенты на этом курсе научатся экспериментировать с наборами данных, полученных с помощью графики, для них это будет хорошее введение. Да, чтобы ещё больше данных скормить ненасытной утробе наших жадных к данным алгоритмов глубокого обучения. Именно. Итак, на этой неделе вы поиграете с этим крутым новым набором данных, и примените его, чтобы попрактиковаться в построении мультиклассового классификатора в TensorFlow. Приглашаем вас приступать.

2(w4)-video2: Moving from binary to multi-class classification (16.MLg_2c)

In the last few lessons, you've been building a binary classifier. One which detects two different types of objects, horse or human, cat or dog, that type of thing. In this lesson, we'll take a look at how we can extend that for multiple classes. Remember when we were classifying horses or human, we had a file structure like this. There were subdirectories for each class, where in this case we only had two. The first thing that you'll need to do is replicate this for multiple classes like this. It's very similar and here you can see that both the training and validation have three subdirectories. One for Rock, one for Paper, and one for Scissors. In these, we can put training and validation images for Rock, Paper, and Scissors.
---------------------------------------------------------------
Последние несколько уроков вы строили бинарный классификатор. Который различает два разных типа объектов: лошади или люди, кошки или собаки, и тому подобное. В этом уроке мы посмотрим, как можно обобщить это на несколько классов. Вспомните, что когда мы классифицировали лошадей и людей, у нас была такая структура файлов. Были подкаталоги для каждого класса, и в этом случае их было только два. В первую очередь, вы должны воспроизвести это для нескольких классов, как вот здесь. Всё почти так же, и можно видеть, что и в тренировочном, и в валидационном каталоге есть по три подкаталога: один для "камня", один для "ножниц", и один для "бумаги". И в них мы можем положить тренировочные и валидационные изображения для камня, ножниц и бумаги.

3(w4)-Introducing the Rock-Paper-Scissors dataset: (16.MLg_2c)

Rock-Paper-Scissors is a dataset containing 2,892 images of diverse hands in Rock/Paper/Scissors poses. It is licensed CC By 2.0 and available for all purposes, but its intent is primarily for learning and research.
https://creativecommons.org/licenses/by/2.0/
Rock Paper Scissors contains images from a variety of different hands, from different races, ages, and genders, posed into Rock / Paper or Scissors and labeled as such. You can download the training set here, and the test set here.
These images have all been generated using CGI techniques as an experiment in determining if a CGI-based dataset can be used for classification against real images. I also generated a few images that you can use for predictions. You can find them here.
Note that all of this data is posed against a white background.
Each image is 300×300 pixels in 24-bit color
You'll see how this dataset can be used to build a multi-class classifier in the next video.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/supplement/HoOHN/introducing-the-rock-paper-scissors-dataset
---------------------------------------------------------------
«Камень-ножницы-бумага» — это набор данных, содержащий 2892 изображения разных рук в позах «камень/ножницы-бумага». Он имеет лицензию CC By 2.0 и доступен для всех целей, но предназначен в первую очередь для обучения и исследований.
https://creativecommons.org/licenses/by/2.0/
«Камень, ножницы, бумага» содержит изображения разных рук, представителей разных рас, возрастов и полов, помещенные в «Камень/ножницы, бумагу» и помеченные соответствующим образом. Вы можете скачать обучающий набор здесь, а тестовый набор здесь.
Все эти изображения были созданы с использованием методов CGI в качестве эксперимента по определению того, можно ли использовать набор данных на основе CGI для классификации реальных изображений. Я также создал несколько изображений, которые вы можете использовать для прогнозов. Вы можете найти их здесь.
Обратите внимание, что все эти данные расположены на белом фоне.
Каждое изображение имеет размер 300×300 пикселей в 24-битном цвете.
В следующем видео вы увидите, как этот набор данных можно использовать для создания многоклассового классификатора.

4(w4)-video3: Explore multi-class with Rock Paper Scissors dataset (16.MLg_2c)

Now, this is a new data set that I created for learning opportunities. It's freely available, and it consists of about 3,000 images. They've all been generated using CGI with a diverse array of models, male and female, and lots of different skin tones, and here's some examples. If you want to download the data sets, you can find them at this URL. It will contain a training set, a validation set, and some extra images that you can download to test the network for yourself. Once your directory is set up, you need to set up your image generator. Here's the code that you used earlier but, note the class mode was set to binary. For multiple classes, you'll have to change this to categorical like this. The next change comes in your model definition where you'll need to change the output layer. For a binary classifier, it was more efficient for you to just have one neuron and use a sigmoid function to activate it. This meant that it would output close to zero for one class and close to one for the other. Now, that doesn't fit for multi-class, so we need to change it, but it's pretty simple. Now, we have an output layer that has three neurons, one for each of the classes rock, paper, and scissors, and it's activated by softmax which turns all the values into probabilities that will sum up to one. So what does that really mean? Consider a hand like this one. It's most likely a paper, but because she has her first two fingers open, and the rest joined, it could also be mistaken as scissors. The output of a neural network with three neurons and a softmax would reflect that, and maybe look like this with a very low probability of rock, a really high one for paper, and a decent one for scissors. All three probabilities would still add up to one. The final change then comes when you compile your network. If you recall with the earlier examples, your loss function was binary cross entropy. Now, you'll change it's a categorical cross entropy like this. There are other categorical loss functions including sparse categorical, cross entropy that you used in the fashion example, and you can of course also use those. Around this for 100 epochs, and I got this chart, it shows the training hits a max at about 25 epochs. So I'd recommend just using not many, and that's all really that you have to do. So let's take a look at it in the workbook.
---------------------------------------------------------------
Итак, вот новый набор данных, который я создал для обучения. Он свободно доступен и состоит из порядка 3000 изображений. Все они сгенерированы с помощью компьютерной графики, с большим разнообразием моделей, мужских и женских, и множеством различных оттенков кожи, вот несколько примеров. Если вы хотите скачать этот набор данных, он находится по этой ссылке. Он содержит тренировочный набор, валидационный набор, и несколько дополнительных изображений, с помощью которых вы можете протестировать сеть. Когда вы задали путь к каталогу, вам надо настроить генератор изображений. Вот код, который вы использовали ранее, но обратите внимание, что class_mode был задан как 'binary'. Для нескольких классов вам нужно изменить его на 'categorical', как здесь. Следующие изменения вас ждут в определении модели, где вам нужно изменить выходной слой. Для бинарного классификатора было эффективнее использовать лишь один нейрон, активируемый сигмоидной функцией. Это значит, что он выдаёт число, близкое к 0, для первого класса, и близкое к 1 — для второго. Но это не годится для нескольких классов, поэтому нам надо изменить его, но это довольно просто. Теперь у нас будет выходной слой с тремя нейронами, по одному для каждого класса: камня, ножниц и бумаги, — и они активируются функцией softmax, которая для каждого класса выдаёт его вероятность, в сумме давая 1. Что же это значит на деле? Посмотрим на такую руку. Она больше похожа на бумагу, но из-за того, что первые два пальца разделены, а остальные сомкнуты, её можно ошибочно принять за ножницы. Вывод нейросети и тремя нейронами и софтмаксом покажет это, и может выглядеть примерно так, с очень низкой вероятностью для камня, высокой для бумаги и умеренной для ножниц. Все три вероятности в сумме дают единицу. И последнее изменение нужно внести, когда вы компилируете сеть. Вспомните, что раньше вашей функцией потерь была бинарная кросс-энтропия. Сейчас вам надо заменить её на категориальную кросс-энтропию, как здесь. Есть и другие категориальные функции потерь, включая разреженную категориальную кросс-энтропию, которую вы использовали в задаче с классификацией одежды, и вы, конечно, можете использовать здесь одну из них. Я запустил обучение на 100 эпох, и получил такой график, показывающий, что при обучении максимум достигается примерно за 25 эпох, так что я бы порекомендовал использовать их не так много. Вот и всё, что вам нужно сделать. Давайте посмотрим на всё это в блокноте.

5(w4)-Check out the code! (Lab 1): (16.MLg_2c)

Now that you've explored the data, and seen how the code can be modified from a binary class classifier to a multi class one, let's take a look at the notebook that implements that for us!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/ungraded_lab/C2_W4_Lab_1_multi_class_classifier.ipynb
---------------------------------------------------------------
Теперь, когда вы изучили данные и увидели, как можно изменить код с бинарного классификатора на многоклассовый, давайте взглянем на блокнот, который реализует это для нас!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/ungraded_lab/C2_W4_Lab_1_multi_class_classifier.ipynb

6(w4)-video4: Train a classifier with Rock Paper Scissors (16.MLg_2c)

In the previous lesson, we looked at how you would go from the binary classifiers we'd been looking at throughout the course, to update it from multi-class classifier. In this video, we'll look at the Rock Paper Scissors workbook and explore how it perform multi-class classification. The first step is to get the data. There are two zip files, one for the training data, and one for the test set. Once we have the data, we'll unzip it into the subdirectories here.
Let's now take a look at some of the files within that. You can see there are 840 of each class and a few filenames. Let's now plot a few of the files so we can see what the data looks like. As we can see, we have a few different hands with different skin colors, and both male and female hands. Let's now build the model. Note that while the images are 300 by 300, we are setting up the image generators to give us 150 by 150 variance. It will resize them on the fly and augment the ones in the training directory. We'll also print out the model if you want to inspect it.
Now, the training begins. I'll speed up the video so that you can see the progress. Keep an eye on the accuracy and the validation accuracy. I'm only training for 25 epochs, based on the chart you saw in the last lesson. But by the time we reach the 10th epoch, we're already doing quite well.
By the time we finish, the training data is above 98% and the validation data is at 95 percent accuracy. This is highly specialized data that's optimized for this lesson and not a great real-world scenario for Rock, Paper, and Scissors. I'll discuss why in a moment but let's first plot the accuracy. We can see the training improving and trending towards one. The validation zig-zags a bit, but it's always between 0.9 and one after the first few epochs. Now, let's explore testing it with some images that it hasn't previously seen.
---------------------------------------------------------------
В предыдущем уроке мы посмотрели, как вы можете перейти от бинарного классификатора, которым мы занимались в течение всего курса, к новому для вас мультиклассовому классификатору. В этом видео мы посмотрим на блокнот для "камень-ножницы-бумага", и исследуем, как он справляется с мультиклассовой классификацией. Первый шаг — получить данные. Есть два zip-файла, один с тренировочным набором, и один с тестовым. Когда мы скачали данные, распакуем их каталог /tmp, тренировочные данные будут в /tmp/rps. Вы видите здесь подкаталоги. Давайте посмотрим несколько файлов оттуда. Вы видите, что к каждому классу относится по 840 файлов, вот несколько их имён. Давайте теперь выведем на экран изображения из нескольких файлов, чтобы посмотреть, на что эти данные похожи. Мы видим несколько разных рук с разным цветом кожи, как мужские, так и женские. Давайте построим модель. Обратите внимание, что хотя размер изображений 300x300, мы настраиваем генератор изображений так, чтобы он нам выдавал изображения размером 150x150. Он изменит их размер на лету и аугментирует изображения из тренировочного каталога. Выведем также сводку о модели, на случай, если вы захотите посмотреть на неё. Начинаем тренировку. Я ускорил видео, и вы можете следить за прогрессом. Смотрите на тренировочную и валидационную долю верных ответов. Я тренирую только 25 эпох, основываясь на графике из предыдущего урока. Когда мы достигаем 10-й эпохи модель уже довольно неплохая. Когда тренировка закончена, у нас доля верных ответов на тренировочном наборе свыше 98%, а на валидационном — около 95%. Дело в том, что это данные, специально подготовленные для этого урока, и не настолько хорошо подходящие под реальные сценарии игры в "камень-ножницы-бумагу". Я расскажу об этом немного позже, а сейчас давайте построим график верных ответов. Мы видимо, что на тренировочных данных показатель улучшается и стремится к единице. Доля верных ответов на валидационных данных немного скачет, но всегда находится между 0.9 и 1 после первых нескольких эпох. Теперь давайте протестируем модель на нескольких изображениях, которые она ещё не видела.

7(w4)-Try testing the classifier: (16.MLg_2c)

In the following video, you'll see Laurence testing the classifier. You should also try it out using the data that you can find here.
F:\Projekt\DOC\ML_Boodcamp\Video\2c_Convolutional Neural Networks in TensorFlow\ColabNotebook_files\week4\rps-test-set
---------------------------------------------------------------
В следующем видео вы увидите, как Лоуренс тестирует классификатор. Вы также должны попробовать это, используя данные, которые вы можете найти здесь.

8(w4)-video5: Test the Rock Paper Scissors classifier (16.MLg_2c)

I've generated a few that you can use to test, they're at the URL in the previous lesson with the training set, test set, and validation set are all link to. Download the RPS validation zip from the link shown and in it, you'll find 33 images of different hand models ones that weren't using the training and validation sets and they're in different poses. Let's now upload one of these to the workbook and we'll try and get what happens. I'm going to pick a paper pose, and the classification comes back as 1-0-0. When using the image generator, the classes come from directories and thus were sorted in alphabetical order. So the first value is for paper and then rock and then scissors. So we can see that this is correct. So if I try another one a scissors, we'll see that the third neuron lights up which is what I would expect. Lets now try a rock, and this one is a larger picture hence the high resin filename, and I want you to see how that would perform. It's slower to upload and it needs to re-scale, but we can see that it gets classified correctly as a rock. I can also upload all the files at once and see classifications for them all. So let's try that. I'm speeding up the video to get past all the uploads. So let's take a look at the classifications that I get back. Remember that the neurons are in the order paper then rock then scissors because it's alphabetical. So we can see that the first one is right. The third one is correct and the same with the fourth and the fifth. So let's keep looking through the list. They mostly seem to be correct. The rest of the data looks like it was classified correctly. So that was a look at multiclass classification. Hopefully, you found it interesting.
---------------------------------------------------------------
Я сгенерировал несколько изображений, которые можно использовать для теста. Они находятся по ссылке из предыдущего урока, там же, где и тренировочный набор, тестовый и валидационный наборы, — все вместе. Скачайте rps_validation.zip по указанной ссылке, и в нём вы найдёте 33 изображения различных рук, не использовавшихся в тестовом и валидационном наборах, и все руки в разных позициях. Давайте загрузим одно из них в блокнот, попробуем и посмотрим, что будет. Я выбираю позицию "бумага", и классификатор выдаёт результат 1-0-0. Когда мы используем генератор изображений, классы берутся из названий каталогов, и идут в алфавитном порядке, так что первое значение — это бумага, потом камень, а потом ножницы. Мы видим, что это так. Попробуем другой файл — "ножницы", мы увидим, что активирован третий нейрон, как мы и ожидали. Давайте попробуем "камень", и это одно из больших изображений, поэтому в его имени есть "hires". И я хочу, чтобы вы увидели, как работает на нём. Оно медленнее загружается, и его нужно масштабировать, но мы видим, что оно верно классифицировано как камень. Также я могу загрузить все файлы сразу, и посмотреть классификацию для них всех. Давайте попробуем. Я ускорю видео, чтобы быстро миновать загрузку. Давайте посмотрим на полученные результаты классификации. Помним, что нейроны идут в таком порядке: бумага, потом камень, потом ножницы, — потому что он алфавитный. Итак, мы видим, что первый определился верно. Это ножницы. Но второй — неверно: это бумага, но наибольшее значение — у третьего нейрона, близкое к единице. А крошечного сигнала в "бумажном" нейроне даже близко недостаточно. Третий — ножницы, и это верно, аналогично для четвёртого и пятого. Продолжим просматривать по списку. Большинство выглядит верно. Пока мы не достигнем файла paper5.png, который, как и ранее, ошибочно классифицирован как ножницы. Давайте посмотрим на изображение. Это очевидно плоская рука. Возможно, что-то в её внешнем виде напоминает ножницы? У модели очень длинные пальцы. Paper9 тоже классифицировано как ножницы, и это очень похожее изображение, особенно, как вы видите, похожи промежутки между пальцами. Давайте посмотрим ещё несколько изображений. Вот ещё одна бумага, которую неправильно классифицировали, и изображение выглядит вот так. Оно очень отличается от других. Но при этом, первые два пальца очень похожи на ножницы. Все последующие данные, похоже, классифицированы правильно. Итак, мы посмотрели на мультиклассовую классификацию. Надеюсь, вам было интересно.

9(w4)-What have we seen so far?: (16.MLg_2c)

You're coming to the end of Course 2, and you've come a long way! From first principles in understanding how ML works, to using a DNN to do basic computer vision, and then beyond into convolutions.
With convolutions, you then saw how to extract features from an image, and you saw the tools in TensorFlow and Keras to build with convolutions and pooling as well as handling complex, multi-sized images.
Through this, you saw how overfitting can have an impact on your classifiers, and explored some strategies to avoid it, including image augmentation, dropout, transfer learning, and more. To wrap things up, you looked at the considerations in your code to build a model for multi-class classification!
---------------------------------------------------------------
Вы подходите к концу курса 2, и вы прошли долгий путь! От первых принципов в понимании того, как работает машинное обучение, до использования DNN для базового компьютерного зрения, а затем до сверток.
С помощью сверток вы увидели, как извлекать функции из изображения, и вы увидели инструменты в TensorFlow и Keras для построения с помощью сверток и объединения, а также для обработки сложных изображений разного размера.
Благодаря этому вы увидели, как переоснащение может повлиять на ваши классификаторы, и изучили некоторые стратегии, чтобы избежать этого, включая увеличение изображения, отсев, перенос обучения и многое другое. Подводя итог, вы рассмотрели соображения в своем коде, чтобы построить модель для классификации нескольких классов!

10(w4)- Week 4 Quiz: (16.MLg_2c)

1) The diagram for traditional programming had Rules and Data In, but what came out?:
1. Answers (+)
2. Binary
3. Machine Learning
4. Bugs
2) Why does the DNN for Fashion MNIST have 10 output neurons?:
1. To make it train 10x faster
2. To make it classify 10x faster
3. Purely Arbitrary
4. The dataset has 10 classes(+)
3)What is a Convolution?:
1. A technique to make images smaller
2. A technique to make images larger
3. A technique to extract features from an image(+)
4. A technique to remove unwanted images
4) Applying Convolutions on top of a DNN will have what impact on training?:
1. It will be slower
2. It will be faster
3. There will be no impact
4. It depends on many factors. It might make your training faster of slower, and a poorly designed Convolytiional layer may even be less efficient than a lain DNN(+)
5) What method on an ImageGenerator is used to normalize the image?:
1. normalize
2. flatten
3. rezize()
4. rescale (+)
6) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk.:
1. A copy will be made, and the copies are augmented
2. A copy will be made, and the originals will be augmented
3. Nothing (+)
4. The images will be edited on disk, so be sure to have a backup
7) Can you use Image augmentation with Transfer Learning?:
1. No - because the layers are frozen so they can't be augmented
2. Yes. It's pre-trained layers that are frozen. So you can augment your images as you train the bottom layers of the DNN with them (+)
8) When training for multiple classes what is the Class Mode for Image Augmentation?:
1. class_mode='multiply'
2. class_mode = 'non_binary'
3. class_mode = 'categorical'(+)
4. class_mode = 'all'

11(w4)-Lecture Notes Week 4: (16.MLg_2c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
opyright Notice
These slides are distributed under the Creative Commons License. DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторском праве
Эти слайды распространяются по лицензии Creative Commons. DeepLearning.AI делает эти слайды доступными для образовательных целей.
https://www.deeplearning.ai
Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные сведения о лицензии см.
https://creativecommons.org/licenses/by-sa/2.0/legalcode

11(w4)-Programming Assignment: Classification: Beyond two classes: (16.MLg_2c)

You have not submitted. You must earn 80/100 points to pass.
Deadline
The assignment was due on Jun 26, 9:59 AM EEST
You can still pass this assignment before the course ends.
Now that you've explored the concepts behind going from binary classification to multi class classification, it's time for another Exercise. In this one you'll use the Sign Language dataset from
https://www.kaggle.com/datamunge/sign-language-mnist
, and attempt to build a multi-class classifier to recognize sign language!
Let's build a multi-class classifier to recognize sign language!
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/assignment/C2W4_Assignment.ipynb#scrollTo=689f1257
This notebook is hosted on github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
You should upload one file:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
parse_data_from_input
train_val_generators
create_model
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
Вы не представили. Вы должны заработать 80/100 очков, чтобы пройти.
Крайний срок
Задание должно было быть выполнено 26 июня в 9:59 по восточному поясному времени.
Вы все еще можете сдать это задание до окончания курса.
Теперь, когда вы изучили концепции перехода от бинарной классификации к многоклассовой, пришло время для другого упражнения. В этом вы будете использовать набор данных языка жестов из
https://www.kaggle.com/datamunge/sign-language-mnist
, и попытайтесь создать многоклассовый классификатор для распознавания языка жестов!
Давайте создадим многоклассовый классификатор для распознавания языка жестов!
Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/assignment/C2W4_Assignment.ipynb#scrollTo=689f1257
Этот блокнот размещен на github, поэтому для сохранения любых изменений вам необходимо создать его копию на вашем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».
Вы должны загрузить один файл:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
parse_data_from_input
train_val_generators
create_model
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

12(w4)-Wrap up: (16.MLg_2c)

Congratulations on finishing Course 2 of this Specialization! Here, you spent a lot of time going over Convolutional Neural Networks:
exploring how to use them with large datasets
taking advantage of augmentation, dropout, regularization, and transfer learning
and of course, looking at the coding considerations between binary or multi-class classification
In Course 3, you'll switch gears and continue with Natural Language Processing, and in particular, work with texts.
---------------------------------------------------------------
Поздравляем с окончанием 2-го курса этой специализации! Здесь вы потратили много времени на сверточные нейронные сети:
изучение того, как использовать их с большими наборами данных
использование преимуществ увеличения, отсева, регуляризации и трансферного обучения
и, конечно же, глядя на соображения кодирования между двоичной или многоклассовой классификацией
На курсе 3 вы переключитесь и продолжите обработку естественного языка и, в частности, работу с текстами.

13(w4)-video6: A conversation with Andrew Ng (16.MLg_2c)

Congratulations on coming to the end of this second course. Just cause you've learned how to build bigger confidence, how to implement data augmentation, how to implement transfer learning as well also how to use multi-class cross size but there's still a lot more to learn. Lot's the examples you've seen so far have used many computer vision. In the next course, you'll learn how to deal with natural language processing to how to work with texts. It's going to be a lot of fun switching gears as well from dealing with pixels to dealing with characters and dealing with words. We'll take a look at how to tokenize words, how to generate embeddings, so that we can learn off of embeddings. An embedding is where we can turn a word into basically a vector in a multi-dimensional space and from the direction that vector points in we can start ascertaining the semantics of that word. We'll be going into all of that and how words also work in sequence and different sequence models for learning what the context of a sentences and what the semantics of the sentence is, yeah. That sounds exciting. So I think natural language processing is really taking off partly because of deep learning. So in the next course, you'll learn a lot about that and give that built some of these exciting models yourself. So let's go to the next course.
---------------------------------------------------------------
Поздравляю с тем, что дошли до конца этого второго курса. Из этого курса вы узнали, как достичь большей надёжности, как реализовать аугментацию данных, как реализовать перенос обучения, а также — как использовать мультиклассовую классификацию. Но многое ещё лишь предстоит узнать. Многие примеры, которые вы уже видели, использовали компьютерное зрение. В следующем курсе вы узнаете, как работать с естественным языком, как работать с текстами. Будет очень увлекательно переключиться от работы с пикселями на работу с символами и словами. Мы посмотрим, как токенизировать слова, как генерировать эмбеддинги, мы многое узнаем про эмбеддинги. Эмбеддинг — это то, с помощью чего мы фактически превращаем слово в вектор в многомерном пространстве, и по направлению, куда этот вектор указывает, мы можем выяснить семантику этого слова. Мы углубимся во всё это: как слова работают в предложении, каковы различные модели последовательностей для изучения контекста предложения, и что такое семантика предложения. Это звучит потрясающе. Я думаю, работа с естественным языком действительно очень много приобрела благодаря глубокому обучению. Так что в следующем курсе вы узнаете многое об этом, и сами построите некоторые из этих впечатляющих моделей. Итак, давайте перейдем к следующему курсу.


17.MLg_3c


(w1)Sentiment in text (17.MLg_3c)

(Настроение в тексте)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video: 38 minutes
Self-study: 1h 27 min
Graded tasks (Tasks to be assessed): 2

(w1) Content (17.MLg_3c)

1. 2. 3. 4.

(w1) Introduction: (17.MLg_3c)

The first step in understanding sentiment in text, and in particular when training a neural network to do so is the tokenization of that text. This is the process of converting the text into numeric values, with a number representing a word or a character. This week you'll learn about the Tokenizer and pad_sequences APIs in TensorFlow and how they can be used to prepare and encode text and sentences to get them ready for training neural networks!
---------------------------------------------------------------
Первым шагом в понимании настроения в тексте и, в частности, при обучении нейронной сети для этого является токенизация этого текста. Это процесс преобразования текста в числовые значения, где число представляет слово или символ. На этой неделе вы узнаете об API-интерфейсах Tokenizer и pad_sequences в TensorFlow и о том, как их можно использовать для подготовки и кодирования текста и предложений, чтобы подготовить их к обучению нейронных сетей!

1(w1)-video1: Introduction, A conversation with Andrew Ng (17.MLg_3c)

Welcome back. In this course, you'll learn how to use TensorFlow to process texts for natural language processing. Unlike images, which come in these regular shaped tensors of pixel intensity values, Text is messier, there are long sentences, there are short sentences. Do you want to process individual characters alphabets or do you wanna process words? So in this course, you learn how to deal with all that. Yes. So like in our first week as well we're going to take a look at what it takes for you to process text because neural networks generally deal in numbers. The zero functions, calculating weights and biases is all numbers. So how are we going to convert our texts into numbers in a sensible way? Given a word like cat, how do you turn that into a set of numbers that you can feed into neural network? Exactly. Then if I have cat, then what's dog going to look like? All of those kind of things. Then multiple length sentences as well. How do we deal with padding them? Or if you've got like a body of words that you use for training, and then you have another body of words that you want to actually predict on, but you're going to have some words in this body that aren't in that one. How do you deal with out of vocabulary tokens and that kind of things? There's going to be a lot of fun. Yeah. So in this first week, you learn how to load in the texts, pre-process it and set up your data so it can be fed to a neural network. I'm really excited. In this course, you'll learn how to deal with texts using TensorFlow. So let's go on to the next video to get started.
---------------------------------------------------------------
Добро пожаловать. На этом курсе вы узнаете, как использовать TensorFlow для обработки текстов на естественном языке. В отличие от изображения, которое может быть представлено в виде регулярной матрицы (тензора) значений яркости пикселей, — текст обладает более сложной структурой, может содержать как длинные, так и короткие предложения. Возникает вопрос: хотим ли мы обрабатывать отдельные буквы алфавита или целые слова? Итак, в этом курсе вы узнаете, как это делается. К примеру, на первой неделе курса мы узнаем, что требуется для того, чтобы обрабатывать текст, потому что нейронные сети обычно оперируют числами. Функции ошибки, вычисление весов и отклонений — это все работа с числами. Каким образом преобразовать текст в числа осмысленным образом? К примеру, слово "кошка", как его перевести в набор чисел, которые можно подать в нейронную сеть? Именно. И если у меня есть преобразование для слова"кошка", то каким образом тогда будет преобразовано слово "собака"? И всё в таком же духе. Кроме того, предложения могут быть разной длины. Как работать с ними? Или, если у вас есть набор слов, которые используются для обучения, и другой набор слов, который вы хотите уметь предсказывать, то, скорее всего, некоторые слова из этого набора не будут представлены в обучающем. Как работать со словами, отсутствующими в словаре, и тому подобным? Это будет очень занимательно. На первой неделе, вы узнаете, как загружать тексты, предобрабатывать их и подготавливать данные таким образом, чтобы их можно было подать в нейронную сеть. Я поистине восхищён. В этом курсе вы узнаете, как работать с текстами при помощи TensorFlow. И чтобы приступить, давайте перейдем к следующему видео.

2(w1)-Where to find the notebooks for this course: (17.MLg_3c)

All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You can simply click the Open in Colab badge at the top of the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this Github repository under the C3 folder. If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
tensorflow-datasets==4.0.1
scikit-learn==1.0.1
pandas==1.1.5
matplotlib==3.2.2
seaborn==0.11.2
---------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы можете просто щелкнуть значок «Открыть в Colab» в верхней части неоцененных лабораторных работ, в то время как для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом репозитории Github в папке C3. Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

3(w1)-video2: Introduction (17.MLg_3c)

In the earlier courses in this specialization, you got an introduction to machine learning and deep learning with a heavy focus on computer vision problems. You learned about neural networks and how they can match patterns to perform classifications. And then how you can give them new data and have them predict what they might be seeing. You learned how to make that a little smarter for images using convolutions to identify the features in the images and classify based on those instead of just matching on raw pixels. This helped you classify images for more real world style ones instead of using a very controlled environment.
In this course we're going to go back to building models but we'll focused on text and how you can build classifier is based on text models. We'll start by looking at sentiment in text, and learn how to build models that understand text that are trained on labeled text, and then can then classify new text based on what they've seen.
When we were dealing with images, it was relatively easy for us to feed them into a neural network, as the pixel values were already numbers. And the network could learn parameters of functions that could be used to fit classes to labels. But what happens with text? How can we do that with sentences and words?
---------------------------------------------------------------
В предыдущих курсах специализации вы прослушали введение в машинное обучение и глубокое обучение c упором на задачи компьютерного зрения. Вы изучили нейронные сети и то, каким образом они могут находить соответствия для решения задач классификации. А затем узнали, каким образом подать на сеть новые данные и научить её догадываться, что на них видно. Вы узнали, как решить эту задачу для изображений более ловко, используя свертки для выделения признаков на изображении и классификации по этим признакам — взамен простого сравнения пикселей. Это помогло классифицировать более реалистичные изображения, а не только сильно ограниченные набором условий*. [где объект крупный и в центре - прим. перев.]
В этом курсе мы вернемся к построению моделей, но сосредоточимся на текстах и на том, как строить классификаторы для них. Мы начнем с рассмотрения эмоциональной окраски текстов, и узнаем, как построить модели для понимания текста, обучающиеся на размеченных данных, чтобы эти модели могли классифицировать новые тексты на основе уже виденных.
Когда мы работали с изображениями, для нас было несложно подать их в нейронную сеть, т.к. значения яркости пикселей уже являются числами. И нейронная сеть может подстроить параметры функций, которые в дальнейшем будут использоваться для классификации. Но как быть с текстами? Как мы можем работать с предложениями и словами?

4(w1)-video3: Word based encodings (17.MLg_3c)

We could take character encodings for each character in a set. For example, the ASCII values. But will that help us understand the meaning of a word? So for example, consider the word 'LISTEN' as shown here. A common simple character encoding is ASCII, the American Standard Code for Information Interchange with the values as shown here. So you might think you could have a word like LISTEN encoded using these values. But the problem with this of course, is that the semantics of the word aren't encoded in the letters. This could be demonstrated using the word 'SILENT ' which has a very different and almost opposite meaning, but with exactly the same letters. So it seems that training a neural network with just the letters could be a daunting task. So how about if we consider words? What if we could give words a value and have those values used in training a network? Now we could be getting somewhere. So for example, consider this sentence, I Love my dog. How about giving a value to each word? What that value is doesn't matter. It's just that we have a value per word, and the value is the same for the same word every time. So a simple encoding for the sentence would be for example to give word 'I' the value one. Following on, we could give the words 'Love', 'my' and 'dog' the values 2, 3, and 4 respectively. So then the sentence, I love my dog would be encoded as 1, 2, 3, 4. So now, what if I have the sentence, I love my cat? Well, we've already encoded the words 'I love my' as 1, 2, 3. So we can reuse those, and we can create a new token for cat, which we haven't seen before. So let's make that the number 5. Now if we just look at the two sets of encodings, we can begin to see some similarity between the sentences. I love my dog is 1, 2, 3, 4 and I love my cat is 1, 2, 3, 5. So this is at least a beginning and how we can start training a neural network based on words. Fortunately, TensorFlow and Keras give us some APIs that make it very simple to do this. We'll look at those next.
---------------------------------------------------------------
Мы могли бы взять коды символов для каждого символа из кодировки. К примеру, значения из ASCII. Но поможет ли это понять смысл слова? Так, например, рассмотрим слово "LISTEN" , как показано здесь. Широко используется кодировка символов ASCII, т.е., "American Standard Code for Information Interchange" [Стандартный Американский Код для Обмена Информацией - прим.], — и здесь показаны её значения. И можно решить, что достаточно закодировать LISTEN, используя эти значения. Но проблема, разумеется, в том, что семантика слова не заложена в буквы. Это можно проиллюстрировать с помощью слова 'SILENT': его смысл совсем другой, практически противоположный, но буквы в слове те же самые. И похоже, что обучение нейронной сети с использованием только букв — это сложная задача. Так, может, стоит рассматривать слова целиком? Что, если бы мы могли присвоить целому слову (числовое) значение, и использовать эти значения для обучения сети? Возможно, это нам что-то даст. К примеру, рассмотрим предложение: "I Love my dog." Давайте присвоим значение каждому слову. Что это за значения — без разницы. Просто каждому слову присвоено отдельное значение, и значения для одинаковых слов всякий раз одинаковы. Таким образом, чтобы закодировать предложение, мы, например, присвоим слову 'I' значение 1. Вслед за этим мы могли бы присвоить словам "Love", "my" и "dog" — значения 2, 3 и 4 соответственно. Тогда предложение "I love my dog" будет закодировано как 1, 2, 3, 4. Что, если теперь взять предложение: "I love my cat"? Мы уже присвоили словам "I", "love" и "my" значения 1, 2 и 3. Так что можно их переиспользовать, и дать новое значение слову "cat", которое мы ранее не встречали. Давайте присвоим ему значение 5. Если мы теперь посмотрим на два набора кодов, то заметим, что эти предложения похожи. "I love my dog" закодировано как 1, 2, 3, 4, а "I love my cat" как 1, 2, 3, 5. Итак, это уже кое-что, мы получаем возможность обучать нейросеть на основе слов. К счастью, TensorFlow и Keras предоставляют API, который сильно облегчает эту задачу. Мы поговорим о нём далее.

5(w1)-video4: Using APIs (17.MLg_3c)

Here's the code to encode the two sentences that we just spoke about. Let's unpack it line by line. Tensorflow and keras give us a number of ways to encode words, but the one I'm going to focus on is the tokenizer. This will handle the heavy lifting for us, generating the dictionary of word encodings and creating vectors out of the sentences. I'll put the sentences into an array. Note that I've already capitalized 'I' as it is at the beginning of the sentence. I then create an instance of the tokenizer. A passive parameter num wards to it. In this case, I'm using 100 which is way too big, as there are only five distinct words in this data. If you're creating a training set based on lots of text, you usually don't know how many unique distinct words there are in that text. So by setting this hyperparameter, what the tokenizer will do is take the top 100 words by volume and just encode those. It's a handy shortcut when dealing with lots of data, and worth experimenting with when you train with real data later in this course. Sometimes the impact of less words can be minimal and training accuracy, but huge in training time, but do use it carefully. The fit on texts method of the tokenizer then takes in the data and encodes it. The tokenizer provides a word index property which returns a dictionary containing key value pairs, where the key is the word, and the value is the token for that word, which you can inspect by simply printing it out. You can see the results here. Remember when we said that the word I was capitalized, note that it's lower-cased here. Here, I've added another sentence, 'You love my dog!' but there's something very different about it. I've added an exclamation after the word 'dog!' Now, should this be treated as a different word than just dog? Well, of course not. That's another thing that the tokenizer does for you. It strips punctuation out. So the results of the code that we saw earlier with this new corpus of data, will look like this. Notice that we still only have 'dog' as a key. That the exclamation didn't impact this, and of course, we have a new key for the word 'you' that was detected. So you've seen the beginnings of handling texts by creating word-based encodings of that text, with some very simple code intensive flow and keras. In the next video, we'll take a look at the code and see how it works.
---------------------------------------------------------------
На экране — программа, кодирующая те два предложения, о которых мы только что говорили. Давайте рассмотрим её построчно. TensorFlow и Keras предоставляют несколько способов кодировать слова, но я сосредоточусь на токенизаторе (tokenizer). Он выполнит за нас всю тяжелую работу по созданию кодового словаря для слов и созданию векторов из предложений. Здесь я помещаю предложения в массив. Обратите внимание, что я написал "Ι" c заглавной буквы, поскольку она в начале предложения. Затем я создаю экземпляр токенизатора и передаю в него параметр num_words (количество слов). Здесь я использую значение 100, которое слишком велико, так как в данных присутствуют только 5 различных слов. Но если вы создаёте набор для обучения на основе большого количества текстов, то обычно не знаете, сколько уникальных слов присутствует в этом тексте. И если задать такое значение гиперпараметра, тогда токенизатор возьмет 100 наиболее часто встречающихся слов, и закодирует их. Это удобно при работе с большим объемом данных, и стоит с ним поэкспериментировать, когда вы позднее в данном курсе будете обучать нейросеть на реальных данных. Иногда слова, встречающиеся редко, могут почти не влиять на точность обучения, но очень сильно увеличивать время обучения. Но используйте параметр осмотрительно. Далее метод 'fit_on_texts' токенизатора получает данные и кодирует их. У токенизатора есть поле 'word_index', возвращающее словарь, содержащий пары ключ-значение, где в качестве ключа — само слово, а в качестве значения выступает соответствующий ему токен. Вы можете изучить этот словарь, просто напечатав его. На слайде представлен результат. Помните , что слово 'I' было написано с заглавной буквы? Обратите внимание, что здесь она строчная. Есть и еще одна вещь, которую токенизатор делает за вас: он удаляет пунктуацию. Польза этой функции видна из следующего примера. Здесь я добавил еще одно предложение: 'You love my dog!' — но здесь есть одно существенное отличие. Я добавил восклицательный знак после слова "dog!". Следует ли считать это слово отличным от просто "dog"? Конечно, нет. Результат выполнения рассмотренной программы на этом новом наборе данных, будет выглядеть так. Обратите внимание, что в качестве ключа у нас по-прежнему только "dog". Восклицательный знак не повлиял на это, и, конечно, у нас появился новый ключ, для обнаруженного здесь слова "you". Итак, вы увидели, как начинается обработка текста через построение для этого текста в TensorFlow и Keras очень простого кода, основанного на словах. В следующем видео мы посмотрим на код и разберемся, как он работает.

6(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community!: (17.MLg_3c)

Hello!
We’ve created a community for you to:
Ask for help on assignments and other course content.
Discuss course topics.
Share your knowledge with other learners.
Build your network
Find out about exciting DeepLearning.AI news, events and competitions!
To go to the community for this course, tick the checkbox below indicating you agree to use the app responsibly, then click on the "Launch App” button.
If you are new to the community, click on the "Launch App" button to create your account and access our community.
We created this User Guide for you.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Be sure to check out the Code of Conduct community guidelines.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Having trouble accessing our community after clicking the “Launch App” button? Fill out this form to explain your issue and we will get back to you.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
We hope to see you in our community soon!
- The DeepLearning.AI team
This course uses a third-party app, [IMPORTANT] Have questions, issues or ideas? Join our Community!, to enhance your learning experience. The app will reference basic information like your name, email, and Coursera ID.
Coursera Honor Code
---------------------------------------------------------------
Привет!
Мы создали для вас сообщество, чтобы:
Попросите помощи в заданиях и другом содержании курса.
Обсудите темы курса.
Поделитесь своими знаниями с другими учащимися.
Создайте свою сеть
Узнайте о захватывающих новостях, событиях и конкурсах DeepLearning.AI!
Чтобы перейти к сообществу для этого курса, установите флажок ниже, указывающий, что вы согласны использовать приложение ответственно, затем нажмите кнопку «Запустить приложение».
Если вы новичок в сообществе, нажмите кнопку «Запустить приложение», чтобы создать учетную запись и получить доступ к нашему сообществу.
Мы создали это Руководство пользователя для вас.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Обязательно ознакомьтесь с принципами сообщества Кодекса поведения.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Возникли проблемы с доступом к нашему сообществу после нажатия кнопки «Запустить приложение»? Заполните эту форму, чтобы объяснить вашу проблему, и мы свяжемся с вами.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
Надеемся скоро увидеть вас в нашем сообществе!
- Команда DeepLearning.AI
В этом курсе используется стороннее приложение. [ВАЖНО] Есть вопросы, проблемы или идеи? Присоединяйтесь к нашему сообществу!, чтобы улучшить свой опыт обучения. Приложение будет ссылаться на основную информацию, такую ​​как ваше имя, адрес электронной почты и идентификатор Coursera.
Кодекс чести Coursera

7(w1)-Check out the code! (Lab 1): (17.MLg_3c)

Ungraded Lab: Tokenizer Basics
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W1/ungraded_labs/C3_W1_Lab_1_tokenize_basic.ipynb

8(w1)-video5: Notebook for lesson 1 (17.MLg_3c)

So here you can see the code that we were looking at in the lesson. First of all, you're going to be using the tokenizer class and this tokenizer class can be found in tensorflow.keras.preprocessing.text. The tokenizer class is going to do all the heavy lifting for us of managing the tokens, turning the sentences into streams of tokens and all that kind of stuff. So let's just take a look at it to begin with. So here I have my list of sentences I just have, I love my dog and I love my cat, note that the I is capitalized. And what the tokenizer is then going to do is that when I create an instance of it, I'm going to pass it a number of words that I want to have as the maximum number of entries in the dictionary. So in this case there's only 5 different words as you can see here, I love my dog and then cat. So this numb words by being bigger than 5 is kind of redundant. But as you're using larger corpuses of texts, if you have thousands of sentences that you want to classify, it's hard for you to end up trying to figure out the unique number of words in all of them. And so what you can do is by passing this parameter and you can say just give me the most common 100 words in the entire corpus, give me the most common 1000 words or whatever. So I'm just defaulting it to 100 here, even though I really don't need any more than 5. Then when I call the fit on texts method of the tokenizer and I pass it this list, what it's going to do is a number of things. The first thing that we're going to be looking at is that it's going to create that word-index for us where the word-index is a list of key value pairs. Where the key is the word and the value is the token for that word and we can print that out here. Other things that it's going to do, we'll take a look at later on but things such as for example turning each of these sentences into a list of tokens instead of those. So you don't have to do that manually but let's just start with the word index. So when I run this code we'll see now that I love my dog. Cat is my dictionary. So it's tokenized, I love my dog and then it's realized that I already had I love in my so it didn't bother with them and then it gave me a token for cats. So I get cat here. And as mentioned in the video, one of the things was that we noticed that it has changed my upper case I to a lowercase I and it's making upper case and lower case that the same thing. So for example, if I were to change this to an I like this, I wouldn't get an additional token, I still just have one token for I. So it's making a case insensitive. In addition to that, of course it's removing punctuation and grammar, not least the spaces have been removed. It's tokenized into words. But for example, if I were to say I, love my cat like this, I will still only have the 5 tokens it's recognized I or for example, if I add a new sentence, you love my dog with an exclamation at the end of it. Now, when I tokenize this, the only thing that I'm going to get is a new one for the word you because it hasn't seen the word you before. As you can see here, we've added a you. So that's it for this basic tokenization. This is the first step that you're going to have in getting text based data ready for training neural networks. This is going to be used with something called an embedding later on. And but before we do that, we just want to look at getting our sentences next into token based lists and making those lists all the same size
---------------------------------------------------------------
Перед вами — код, который мы рассматривали на данном занятии. Прежде всего, мы используем класс Tokenizer, и этот класс можно найти в модуле tensorflow.keras.preprocessing.text. Класс Tokenizer возьмёт на себя всю основную работу по обработке токенов, преобразованию предложений в поток токенов, и так далее. Так что давайте сперва разберёмся с ним. Вот мой список предложений: "I love my dog" и "I love my cat". Обратите внимание, что I — с заглавной буквы. И вот что с ними будет делать Tokenizer: когда я создам его экземпляр, то передам в конструктор число слов — это нужная мне максимальная размерность словаря. Как видите, в нашем случае во входных данных — всего 5 различных слов: I, love, my, dog, cat. Так что значение num_words, превышающее 5, будет избыточным. Но при использовании более крупных корпусов текстов, когда нужно классифицировать тысячи предложений, будет непросто определить число уникальных слов по всему корпусу. И в таком случае можно, задавая этот параметр, указать: "Нужно взять только 100 слов, чаще всего используемых в корпусе", или взять 1000 самых частотных слов, и т.п. Так что здесь я заложу 100, хотя на самом деле мне пока нужно не более 5. Затем я вызываю у токенизатора метод fit_on_texts, передавая в него список. При этом выполняется ряд действий. Во-первых, внутри будет создан индекс слов word_index, представляющий собой список пар ключ-значение. Ключом выступает слово, а значением — его токен. Здесь мы выводим этот список. Кроме того, выполняются и другие действия, мы их рассмотрим чуть позже, скажу лишь, что это, например, преобразование каждого предложения в список токенов, так что не придётся это делать вручную. Пока же рассмотрим индекс слов. Если выполнить этот код, в результате мы видим словарь, содержащий I, love, my, dog и cat. Сначала было разобрано предложение "I love my dog", а затем оказалось, что слова I, love и my уже есть, так что незачем снова их брать, и нужен лишь новый токен для cat. Так что далее идёт cat. В числе прочего, я упоминал на уроке, что здесь I в верхнем регистре заменено на написание в нижнем, i. Тем самым верхний и нижний регистр сводятся к одному и тому же. Так, например, если заменить в этом предложении I на i, то дополнительного токена не появится, будет всё так же один токен для i. Так что здесь вводится нечувствительность к регистру. Кроме того, при обработке выбрасываются пунктуация и грамматика — во всяком случае, исключаются пробелы. Происходит разбивка на слова. И если я, например, напишу так: "I, love my cat" — то по-прежнему получу лишь 5 токенов, среди которых будет и 'i'. Если же добавить новое предложение с восклицательным знаком в конце: "You love my dog!" — то при его разборе на токены я получу лишь один новый, для слова "you", поскольку такого слова прежде не встречалось. Как видите, здесь добавилось 'you'. На этом завершаем общий обзор токенизации. Это первый шаг в подготовке текстовых данных к обучению на них нейронных сетей. Далее мы будем им пользоваться в сочетании с так называемыми эмбеддингами. Но перед этим нам нужно посмотреть, как преобразовать предложения в списки токенов, и что сделать, чтобы эти списки были одинаковой длины.

9(w1)-video6: Text to sequence (17.MLg_3c)

In the previous video, you saw how to tokenize the words and sentences, building up a dictionary of all the words to make a corpus. The next step will be to turn your sentences into lists of values based on these tokens. Once you have them, you'll likely also need to manipulate these lists, not least to make every sentence the same length, otherwise, it may be hard to train a neural network with them. Remember when we were doing images, we defined an input layer with the size of the image that we're feeding into the neural network. In the cases where images where differently sized, we would resize them to fit. Well, you're going to face the same thing with text. Fortunately, TensorFlow includes APIs to handle these issues. We'll look at those in this video. Let's start with creating a list of sequences, the sentences encoded with the tokens that we generated and I've updated the code that we've been working on to this. First of all, I've added another sentence to the end of the sentences list. Note that all of the previous sentences had four words in them. So this one's a bit longer. We'll use that to demonstrate padding in a moment. The next piece of code is this one, where I simply call on the tokenizer to get texts to sequences, and it will turn them into a set of sequences for me. So if I run this code, this will be the output. At the top is the new dictionary. With new tokens for my new words like amazing, think, is, and do. At the bottom is my list of sentences that have been encoded into integer lists, with the tokens replacing the words. So for example, I love my dog becomes 4, 2, 1, 3. One really handy thing about this that you'll use later is the fact that the text to sequences called can take any set of sentences, so it can encode them based on the word set that it learned from the one that was passed into fit on texts. This is very significant if you think ahead a little bit. If you train a neural network on a corpus of texts, and the text has a word index generated from it, then when you want to do inference with the train model, you'll have to encode the text that you want to infer on with the same word index, otherwise it would be meaningless. So if you consider this code, what do you expect the outcome to be? There are some familiar words here, like love, my, and dog but also some previously unseen ones. If I run this code, this is what I would get. I've added the dictionary underneath for convenience. So I really love my dog would still be encoded as 4, 2, 1, 3, which is 'I love my dog' with 'really' being lost as the word is not in the Word Index, and 'my dog loves my manatee' would get encoded to 1, 3, 1, which is just 'my dog my'.
---------------------------------------------------------------
В предыдущем видео вы видели, как токенизировать слова и предложения, создавать словарь всех слов, составляющих корпус. Следующий этап — преобразовать предложения в списки значений на основе этих токенов. Когда вы их получите, вам, вероятно, также понадобится обработать эти списки, не в последнюю очередь, для того, чтобы выровнять их по длине — в противном случае, их трудно будет использовать в обучении нейронной сети. Помните, когда мы работали с изображениями, то определяли размер входного слоя, равный размеру изображения, передаваемого в нейронную сеть? А когда изображения были разных размеров, мы масштабировали их к нужному размеру. При работе с текстом возникает та же задача. К счастью, у TensorFlow есть API для решения этих проблем. Мы рассмотрим его в этом видео. Давайте начнём с создания списка предложений, где предложения закодированы токенами, которые мы сгенерировали. Я обновил наш рабочий код до такого вида. Во-первых, я добавил ещё одно предложение в конец списка. Заметьте, что во всех предыдущих предложениях было по четыре слова. А это — подлиннее. Скоро мы используем его для демонстрации дополнения. А вот второй изменённый участок кода, где я просто вызываю метод токенизатора, чтобы перевести текст в последовательность, и он вернёт мне набор последовательностей. И если я запущу этот код, то вот что он выведет. Сверху — новый словарь. С новыми токенами для новых слов, таких как amazing, think, is и do. Внизу — мой список предложений, закодированных списками целых чисел, где слова заменены токенами. Например, "I love my dog" становится 4, 2, 1, 3. У метода texts_to_sentences есть одно большое удобство, заключающееся в том, что при вызове можно передать любой набор предложений, и он закодирует их по набору слов, которые узнал из текста, переданного в fit_on_texts. Если подумать чуть наперёд, это очень важная вещь. Если вы тренируете нейросеть на корпусе текстов, и у вас есть индекс слов для данного корпуса, тогда для использования выводов обученной сети придётся кодировать тексты, передаваемые ей, тем же самым индексом слов, иначе результат будет бессмыслицей. Итак, посмотрите на этот код, что он, по-вашему, выведет? Здесь есть несколько знакомых слов, как love, my и dog, но есть также несколько незнакомых. Если я запущу этот код, то вот что я получу. Я добавил ниже словарь для удобства. Итак, "I really love my dog" будет закодировано как 4, 2, 1, 3, что значит "I love my dog", а слово "really" потерялось, поскольку его нет в индексе. А "my dog loves my manatee" будет закодировано как 1, 3, 1, что значит "my dog my".

10(w1)-video7: Looking more at the Tokenizer (17.MLg_3c)

So what do we learn from this? First of all, we really need a lot of training data to get a broad vocabulary or we could end up with sentences like, my dog my, like we just did. Secondly, in many cases, it's a good idea to instead of just ignoring unseen words, to put a special value in when an unseen word is encountered. You can do this with a property on the tokenizer. Let's take a look. Here's the complete code showing both the original sentences and the test data. What I've changed is to add a property oov token to the tokenizer constructor. You can see now that I've specified that I want the token oov for outer vocabulary to be used for words that aren't in the word index. You can use whatever you like here, but remember that it should be something unique and distinct that isn't confused with a real word. So now, if I run this code, I'll get my test sequences looking like this. I pasted the word index underneath so you can look it up. The first sentence will be, i out of vocab, love my dog. The second will be, my dog oov, my oov Still not syntactically great, but it is doing better. As the corpus grows and more words are in the index, hopefully previously unseen sentences will have better coverage. Next up is padding. As we mentioned earlier when we were building neural networks to handle pictures. When we fed them into the network for training, we needed them to be uniform in size. Often, we use the generators to resize the image to fit for example. With texts you'll face a similar requirement before you can train with texts, we needed to have some level of uniformity of size, so padding is your friend there.
---------------------------------------------------------------
Итак, чему мы здесь научились? Прежде всего, нам требуется очень много обучающих данных, чтобы собрать большой словарный запас, иначе мы можем получить предложения вроде "my dog my" (моя собака моего), как у нас только что вышло. Во-вторых, во многих случаях полезнее не игнорировать неизвестные слова, а вставлять специальное значение, когда встречается неизвестное слово. Это можно задать специальным параметром токенизатора. Давайте посмотрим. Вот весь код, показывающий как исходные предложения так и тестовые данные. Я изменил его, добавив параметр oov_token в вызов конструктора токенизатора. Как видите, я указал, что хочу для слов, которых нет в индексе, использовать токен &lt;OOV&gt;, означающий "нет в словаре" [Out Of Vocabulary]. Вы можете использовать любое значение, только помните, что оно должно быть уникальным, чтобы его нельзя было перепутать с настоящим словом. Итак, если я сейчас запущу этот код, то получу вывод тестовых предложений в таком виде. Ниже я привёл индекс слов, чтобы можно было с ним сверяться. Первое предложение будет: "I &lt;нет_в_словаре&gt; love my dog". Второе будет: "my dog &lt;не_в_словаре&gt; my &lt;не в словаре&gt;". Всё ещё небезупречно синтаксически, но уже лучше. По мере того, как корпус растёт, и в индексе становится всё больше слов, есть надежда, что не попадавшиеся ранее фразы будут содержать меньше незнакомых слов. Переходим к выравниванию. Как мы уже говорили, когда строили нейросеть для работы с изображениями: чтобы подать их в сеть для тренировки, нам нужно было сделать их одного размера. Обычно для изменения размера изображений используют генераторы. При работе с текстами существует аналогичное требование: прежде чем обучать на текстах, нужно как-то обеспечить однородность по длине, и выравнивание вам в этом поможет.

10(w1)-video8: Padding (17.MLg_3c)

So I've made a few changes to the code to handle padding. Here's the complete listing and we'll break it down piece by piece. First, in order to use the padding functions you'll have to import pad sequences from tensorflow.keras.preprocessing.Sequence. Then once the tokenizer has created the sequences, these sequences can be passed to pad sequences in order to have them padded like this. The result is pretty straight forward. You can now see that the list of sentences has been padded out into a matrix and that each row in the matrix has the same length. It achieved this by putting the appropriate number of zeros before the sentence. So in the case of the sentence 5-3-2-4, it didn't actually do any. In the case of the longer sentence here it didn't need to do any. Often you'll see examples where the padding is after the sentence and not before as you just saw. If you, like me, are more comfortable with that, you can change the code to this, adding the parameter padding equals post. You may have noticed that the matrix width was the same as the longest sentence. But you can override that with the maxlen parameter. So for example if you only want your sentences to have a maximum of five words. You can say maxlen equals five like this. This of course will lead to the question. If I have sentences longer than the maxlength, then I'll lose information but from where. Like with the padding the default is pre, which means that you will lose from the beginning of the sentence. If you want to override this so that you lose from the end instead, you can do so with the truncating parameter like this. So you've now seen how to encode your sentences, how to pad them and how to use Word indexing to encode previously unseen sentences using out of vocab characters. But you've done it with very simple hard-coded data. Let's take a look at the coded action in a screencast and then we'll come back and look at how to use much more complex data.
---------------------------------------------------------------
Итак, я слегка изменил код, добавив выравнивание. Вот весь код, мы разберём его по частям. Во-первых, чтобы использовать выравнивание, нужно импортировать pad_sequences из tensorflow.keras.preprocessing.sequence. Затем, когда токенизатор создал последовательности, нужно передать их в pad_sequences, чтобы получить их одинаковой длины, как здесь. Результат довольно очевиден. Вы видите, что список предложений был дополнен до матрицы, и теперь все строки матрицы — одной и той же длины. Это достигнуто размещением соответствующего количества нулей перед каждым предложением. В случае предложения 5, 3, 2, 4, добавлены три нуля. А в случае более длинного предложения ничего не надо было делать. Вам могут часто попадаться примеры, когда выравнивание производится в конце предложения, а не перед словами, как здесь. Если вы, как и я, находите это более удобным, то можете изменить код вот так, добавив параметр padding='post'. Вы могли заметить, что ширина матрицы была равна длине самого длинного предложения. Но это можно изменить, использовав параметр maxlen. Например, если вы хотите, чтобы в предложении было не больше пяти слов, то установите maxlen=5, как здесь. Разумеется, отсюда следует вопрос: а если предложения будут длиннее maxlen, то я потеряю информацию, но с какого конца? Как и в случае с дополнением, значение по умолчанию — 'pre' (перед), это значит, что вы потеряете слова из начала предложения. Если вы хотите это изменить, чтобы терять слова в конце, то можете указать параметр truncating='post', как здесь. Итак, вы теперь увидели, как закодировать предложения, как их выравнивать, и как использовать индекс слов для кодирования ранее незнакомых предложений, используя специальный символ "нет_в_словаре". Но вы всё это делали на простейших зашитых в код данных. Давайте поглядим демонстрацию работы этого кода, а затем вернёмся и посмотрим, как использовать гораздо более сложные данные.

11(w1)-Check out the code! (Lab 2): (17.MLg_3c)

Ungraded Lab: Generating Sequences and Padding
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W1/ungraded_labs/C3_W1_Lab_2_sequences_basic.ipynb

12(w1)-video9: Notebook for lesson 2 (17.MLg_3c)

Let's take a look at some of the basic text preprocessing that we've been doing. First of all, we're going to use a couple of APIs in TensorFlow. There's the tokenizer and there's pad sequences. The tokenizer can be found in tensorflow.keras.preprocessing.text and pad sequences can be found in tensorflow.keras.preprocessing.sequence. Our initial corpus of work that we're going to tokenize based off of is listed here. This is my list of sentences. I love my dog, I love my cat. You love my dog, and do you think my dog is amazing? On the tokenizer, I'm going to instantiate a new tokenizer. I'm going to say the maximum number of words in its corpus should be 100. Obviously we have a less than 100 words here or 100 different, unique and distinct words here. I'm also going to specify them out of vocabulary token should look like this. I'm just going to say it's OOV. I can put anything I want in here. But it should be always something that you wouldn't expect to see in the body of text so that's why I put angle brackets and OOV like this. Next, when I say tokenizer.fitontexts sentences, what it will then do is it's going to generate a tokenizer by creating a unique set of key values for the unique words that are in here. I will become a key love or become a key, those kind of things. It's going to create a word index where there are key value pairs, where a word is the key and that key has a value. For example, love becomes a key, I becomes a key, dog becomes a key. Those kind of things. That word index, I can then pull out of the tokenizer just by calling its word index property. I can get a word index variable that we can take a look at. The next thing is to be able to use sequences is on the tokenizer. It will then turn the text sentences that it has into sequences, replacing each word in the sentence with the value of the key for that particular word. For example, if the word I may have the key 2, and love has the key 3. Instead of saying I love, I'd have 2, 3 in a sequence, that type of thing. That's going to give me the sequences. Next, I'm going to use pads sequences to make all of these sequences the same size or the same width. You see some of these sentences have four words in them. Some of them have more, I believe this got seven words in this one. When we're training a neural network, we do want to have all of the data to be the same size. If you remember when we were doing it with convolutional neural networks, in some cases, like with Fashion-MNIST, the data was always 28 by 28. Or in other cases, like with the cats and dogs or horses versus humans, we resized the data as we were loading it. Pads sequences is our friend for that. In this case, when I take pad sequences, I'm going to pass in the sequences that we just generated. I'm going to specify a couple of parameters, padding equal to post and truncation equals post. The idea with these is that if my sentence is shorter than the width of the array, it's going to pad my sentence. The default experience with pad sequences is that the padding will be before the sentence. For example, in this case we have seven words in the sentence. In this case we have four. All three of these sentences would be padded with three zeros before the tokens for the actual words in the sentence. It'll be 0,0,0 token for I, token for love, token for my, that kind of thing. By specifying padding equals post, we do it the other way round where the zeros come after the sentence. Now it's really up to you how you do it. I tend to prefer it to be after the sentence so I can read the sentence from the beginning because I read left to right. But it's up to you and your scenario. What do you think is best? The default is pre. I'm overriding the default here by specifying post. Similarly, if we decide to specify the width of the array that we're going to be using. For example, in this case there are seven words and we only want it to be five words by saying maxlen equals five, like this. What will then happen is the sentence will be truncated into five. The default behavior is to truncate from the beginning by specifying truncating equals post will truncate from the end. In this case, if the maxlen is five, we'll take the first five words; do you think my dog and we'll lose the last two words. If we didn't have truncating equals posts, it would default to pre or if we set it to pre like this, then it will take the last five words which is think my dog is amazing, that type of thing. I'm just going to change that back to post. I'm going to get rid of maxlen equals 5 for the moment. Then we'll print out the word index that we generated, the sequences that we generated, and the padding sequences that we generated. Let's run it now and we can take a look at them.
If you remember the sentences, I love my dogs, I love my cat, you love my dog, do you think my dog is amazing? Here's the word index that was generated from them. The out of vocabulary token is value 1, my is 2, love is 3, dog is 4, I is 5, etc. Now if we look at the sequences that are created for us. If you remember the first sentence was, I love my dog. If you look at 5,3,2,4, I is 5, love is 3, my is 2, dog is 4 The second sentence was, I love my cat. I is 5, love is 3, my is 2, cat is 7, etc. These are our four sentences have been encoded into these sequences. Now when we do the padded sequences so that we get them all the same size. If you can see here, our first three sentences are four in length. That's this, this, and this. You'll see that they've been padded into, of zero characters at the end to make the right length. Then our final sentence, which was the longer one, the matrix has the same width as that sentence. So if up here, if I had said maxlen equals five and run it. Now we'll see my padded sequences have changed so that the fours are only padded out by one character to make five. My final sentence, 8,6,9,2,4 has lost these last three characters to make it the same width because my truncating equals post. If I remove truncating equals post, and actually I remove padding equal to post as well. We can see what happens. We'll see now that because my padding is pre, these three shorter sentences are prefixed by a zero. Because my truncation is pre, we'll see we are taking the last five characters in this one. There's no padding needed, but the truncation is off the front. That's really how tokenizer and padding works to help you with your text preprocessing. There's some pretty cool stuff going on in there. Now the second thing was to take a look at words that the tokenizer wasn't fixed to. If you remember when we created the tokenizer and the list of tokens in here are just from these sentences. When we start looking at sentences that are different from these, for example, I really love my dog. Instead of I love my dog, we'll notice that we're going to get an out of vocabulary character for this, because this one hasn't been learned. This becomes pretty important later on as you're training neural networks with this data. Because if you're just going to train it on the tokens that are in here, it's going to get harder to classify sentences like these because there's words that the tokenizer hasn't seen before, and therefore that the neural network isn't going to be trained on. Again, it's a classic case of the more training data you have, the better. But let's take a look at how the tokenizer will behave in this scenario anyway. In this case, I'm going to create a test sequence from the test data where I'm just using tokenizer again and I'm passing in the test data to generate some sequences. I'm going to print those out and then I'm going to pad those. Again, you can see I'm padding them, I'm not specifying any behavior here. The maximum length will be the length of the longest sentence. Padding will be pre and truncation will be pre. If I run that and we take a look at them. Now we can see my test sequences gets quite interesting because I said I really loved my dog. My test sequence is 5, 1, 3, 2, 4. Five is I, one of course is the out of vocabulary token, and then 3,2,4 are love my dog. I blank, love my dog is what the test sequence with effectively look like. This sentence, my dog loves my manatee. The word loves is different from the word love so there's no token for it and of course there's no token for manatee. But we have seen my dog and my before. So we end up with 2,4,1,2,1. Two of course is my, four is dog, one is out of vocabulary, two is my, and one is out of vocabulary. I get my dog blank my blank. Then when I pad the sequences out using this code, the 5,3,1,4 will stay the same. The 2,4,1,2,1 will stay the same because the sentences are the same length, so no padding and they'll truncation is necessary. Of course, if I had said something here like maxlen equals 10, and then I run it. We'll get lots of padding and because the default padding experience is pre, it'll be padded beforehand. That's a basic look at how to use tokenizer and how to use pad sequences to do text preprocessing. In the next video, we're going to then take a look at loading much bigger datasets instead of just these simple hard-coded ones and taking a look at what tokenizer and padding we'll do for them
---------------------------------------------------------------
Давайте же рассмотрим действия по самой простой предобработке текста. Первое: мы будем пользоваться некоторыми функциями из TensorFlow. Так что импортируем здесь Tokenizer и pad_sequences. Tokenizer находится в модуле tensorflow.keras.preprocessing.text, а pad_sequences — в модуле tensorflow.keras.preprocessing.sequence. Далее идёт наш изначальный корпус текстов, с которым мы будем работать. Это список моих предложений: "I love my dog", "I love my cat", "You love my dog!" и "Do you think my dog is amazing?" Что касается токенизатора, то я создаю его новый экземпляр, и указываю, что максимальное число слов для данного корпуса должно быть 100. Очевидно, у нас меньше 100 слов, менее 100 различных, уникальных слов. Также я задаю отдельный токен "нет в словаре", который будет выглядеть так: это будет строка "<OOV>". Сюда можно подставить любое значение, какое захочется. Но оно обязательно должно быть таким, чтобы не было шансов встретить его в корпусе текстов — вот почему я использовал здесь OOV в угловых скобках. Далее следует строка tokenizer.fit_on_texts(sentences), где происходит разбивка на токены, состоящая в создании уникальной пары "ключ-значение" для каждого уникального слова в корпусе. Так что ключами станут слова "I", "love", и так далее. При этом будет создан индекс слов word_index, в котором и хранятся эти пары "ключ-значение", где ключом является слово, и ему соответствует некое значение. Так, например, "love" будет ключом, а также "I", "dog", и так далее. Данный индекс слов я затем получаю из токенизатора простым обращением к атрибуту word_index. Можно завести для него переменную word_index, чтобы изучать её содержимое. Следующим шагом для использования последовательностей токенов нужно превратить при помощи токенизатора имеющийся текст в последовательности, где каждое слово предложения заменяется на значение, соответствующее данному ключу. Так, например, у слова "I" может быть значение 2, а у слова "love" — 3, И тогда вместо "I love" получится последовательность [2, 3], и т.п. Вот так я получаю последовательности. Далее я применяю pad_sequences, чтобы все последовательности стали одного размера, одной длины. Как видите, в некоторых предложениях было по четыре слова, а в других — больше, вот в этом, кажется, их семь. Но при обучении нейронной сети нам нужно, чтобы все данные были одной размерности. Если помните, при работе со свёрточными нейронными сетями у нас в некоторых случаях, таких как набор Fashion-MNIST, данные всегда были размером 28x28. А в других случаях, как в наборах "кошки и собаки" и "лошади и люди", мы меняли размерность данных при их загрузке. В данном случае, нас выручает pad_sequences. Так что здесь при вызове pad_sequences я передаю в вызов последовательности, которые мы только что сгенерировали. Кроме того, я указываю ещё два параметра: padding='post' и truncating='post'. Их смысл в том, что когда предложение оказывается короче, чем размерность массива, то данное предложение будет дополнено. По умолчанию pad_sequences дополняет последовательность спереди. Например, в данном случае у нас в предложении семь слов, а в данном случае — четыре. Все эти три предложения будут дополнены тремя нулями перед токенами, соответствующими самим словам предложения. Так что будет 0, 0, 0, затем — токен для "I", токен для "love", для "my", и так далее. Задавая padding='post', мы делаем всё наоборот: нули добавляются после токенов предложения. Тут вам решать, как поступать. Лично я предпочитаю дополнение в конце предложения, чтобы можно было читать его начало, ведь я читаю слева направо. Но в вашем случае решать вам, как вам лучше. По умолчанию дополнение в начало, 'pre'. Я переопределяю значение по умолчанию, указав здесь 'post'. Аналогичным образом, если нам захотелось задать длину используемого массива — например, в данном случае слов семь, а нам захочется брать, скажем, всего пять слов, то задав параметр maxlen = 5, мы добьёмся того, что предложение будет обрезано до пяти слов. По умолчанию обрезка происходит в начале предложения, но если задать truncating='post', то обрезка будет идти с конца. Так, если для данного случая задать maxlen=5, то мы возьмём только первые пять слов: "Do you think my dog" — и потеряем последние два. Если бы мы не задали truncating='post', то по умолчанию оно равнялось бы 'pre' (или можно задать 'pre' явным образом) — и тогда будут использованы последние пять слов, то есть "think my dog is amazing", и т.п. Верну значение 'post' обратно и избавлюсь на время от maxlen=5. Теперь выведем построенный индекс слов и те последовательности, что мы сгенерировали, а также выровненные последовательности. Давайте запустим код и посмотрим результат.
Если помните, то предложения были такими: "I love my dog", "I love my cat", "You love my dog!" и "Do you think my dog is amazing?" И вот индекс слов, созданный по этим предложениям. Токен <OOV> получил значение 1, "my" — 2, "love" — 3, "dog" — 4, "i" — 5, и т.д. Если же посмотреть на созданные последовательности токенов, то, если помните, первым было предложение "I love my dog", и если посмотреть на 5,3,2,4, то "i" — это 5, "love" — это 3, "my" — 2, "dog" — 4. Вторым предложением было "I love my cat". "i" — это 5, "love" — это 3, "my" — 2, "cat" — 7, и т.д. Это четыре наших предложения, закодированные в виде последовательностей токенов. Если теперь выполнить их выравнивание, чтобы они все были одной длины, то, как вы здесь видите, первые три последовательности были длиной в 4 слова, вот они. Как видите, они были дополнены нулями в конце до нужной длины. А последнее предложение, самое длинное, сохранило прежнюю свою длину. Если же выше задать maxlen=5 и запустить код снова, то теперь видно, что выровненные последовательности изменились: те, что были длиной по четыре, дополнены лишь одним символом до пяти, а последнее предложение, 8,6,9,2,4, — потеряло последние два символа при приведении к единой длине, поскольку я задал truncating='post'. Если убрать truncating='post', а заодно и padding='post', то вот что будет. Поскольку теперь дополнение происходит в начало, трём более коротким предложениям предшествуют нули. А поскольку обрезка тоже идёт от начала, то мы видим, что в последнем предложении берутся последние пять элементов. Дополнять здесь не требуется, а вот обрезка идёт из начала. Вот так работают токенизатор и дополнение последовательностей, помогая подготовить текст. Довольно любопытная штука. Второй пунктом было посмотреть, какие слова не участвовали в построении индекса токенов. Если помните, когда мы создавали токенизатор и список токенов, то использовали только эти предложения. И если брать предложения, отличающиеся от исходных, например, "I really love my dog", вместо "I love my dog", то мы увидим, что здесь появится символ "нет в словаре" для "really", потому что этого слова не было при обучении. Далее этот момент будет играть важную роль при обучении нейронной сети на таких данных, ведь если обучать её только на имеющихся здесь токенах, то будет нелегко классифицировать предложения вроде этих двух, потому что в них есть слова, которых токенизатор прежде не встречал, и потому нейросеть на них не будет обучена. Это ещё один классический случай, когда чем больше обучающих данных — тем лучше. Но давайте всё-таки посмотрим, как токенизатор поведёт себя в данном случае. Здесь я создаю тестовую последовательность на основе тестовых данных, при этом повторно используя токенизатор и передавая ему тестовые данные для построения последовательностей. Я их выведу, а затем применю к ним выравнивание. Как видите, здесь при выравнивании я не задаю никаких параметров. Поэтому в качестве максимальной длины будет использована длина самого длинного предложения, дополнение будет происходить спереди, и обрезка тоже. Запустим код и посмотрим, что вышло. Мы видим, что тестовые последовательности выглядят довольно любопытно, ведь я сказал "I really love my dog", и получилась последовательность 5, 1, 3, 2, 4. 5 — это "i", а 1 — это, разумеется, токен <OOV>, а 3, 2, 4 — это "love", "my", "dog". Так что в результате тестовая последовательность выглядит так: "I _ love my dog". А в следующем предложении, "My dog loves my manatee", слово "loves" отличается от слова "love", так что для него нет токена, а также, разумеется, его нет и для "manatee". Но "my", "dog" и "my" мы уже встречали, так что получается 2, 4, 1, 2, 1. 2 — это, разумеется, "my", 4 — "dog", 1 — это "нет в словаре", 2 — "my", и снова 1 — OOV. Итого, я получил: "My dog _ my _". Затем я выравниваю эти последовательности данной строкой кода, и 5, 1, 3, 2, 4 остаётся без изменений, и 2, 4, 1, 2, 1 — тоже без изменений, потому что эти последовательности — одинаковой длины, и не нужно ни дополнения, ни обрезки. Разумеется, если здесь задать, скажем, maxlen=10, и запустить этот код, то появится масса дополнительных символов, и поскольку по умолчанию дополнение идёт в начало, то дополнение произойдёт в начало. Мы посмотрели в общих чертах, как пользоваться токенизатором и выполнять выравнивание последовательностей при подготовке текстов. В следующем видео мы посмотрим загрузку более крупных наборов данных вместо данных простых наборов, заданных в коде. А также посмотрим, что с ними сделают токенизатор и выравнивание.

13(w1)-video10: Sarcasm, really? (17.MLg_3c)

So far this week, you've been looking at texts, and how to tokenize the text, and then turn sentences into sequences using the tools available in TensorFlow. You did that using some very simple hard-coded sentences. But of course, when it comes to doing real-world problems, you'll be using a lot more data than just these simple sentences. So in this lesson, we'll take a look at some public data-sets and how you can process them to get them ready to train a neural network. We'll start with this one published by Rishabh Misra with details on Kaggle at this link. It's a really fun CC0 public domain data-set at all around sarcasm detection. Really? Yeah, really. This data-set is very straightforward and simple, not to mention very easy to work with. It has three elements in it. The first is sarcastic, is our label. It's a one if the record is considered sarcastic otherwise it's zero. The second is a headline, which is just plain text and the third is the link to the article that the headline describes. Parsing the contents of HTML, stripping out scripts, and styles, etc, is a little bit beyond the scope of this course. So we're just going to focus on the headlines. If you download the data from that Kaggle site, you'll see something like this. As you can see, it is a set of list entries with name-value pairs where the name is article link, headline and is_sarcastic and the values are as shown. To make it much easier to load this data into Python, I made a little tweak to the data to look like this, which you can feel free to do or you can download my amended data-set from the link in the co-lab for this part of the course. Once you have the data like this, it's then really easy to load it into Python. Let's take a look at the code. So first you need to import JSON. This allows you to load data in JSON format and automatically create a Python data structure from it. To do that you simply open the file, and pass it to json.load and you'll get a list containing lists of the three types of data: headlines, URLs, and is_sarcastic labels. Because I want the sentences as a list of their own to pass to the tokenizer, I can then create a list of sentences and later, if I want the labels for creating a neural network, I can create a list of them too. While I'm at it, I may as well do URLs even though I'm not going to use them here but you might want to. Now I can iterate through the list that was created with a for item in data store loop. For each item, I can then copy the headline to my sentences, the is_sarcastic to my labels and the article_link to my URLs. Now I have something I can work with in the tokenizer, so let's look at that next.
---------------------------------------------------------------
Итак, на этой неделе вы смотрели на тексты, на то, как токенизировать тексты и затем превращать предложения в последовательности, используя инструменты, доступные в TensorFlow. Вы делали это, используя очень простые, жёстко запрограммированные предложения. Но, конечно, когда дело дойдёт до настоящих задач, вы будете использовать намного больше данных, чем только эти простые предложения. Итак, в этом уроке мы посмотрим на несколько общедоступных наборов данных и на то, как их обработать, чтобы на них можно было тренировать нейросеть. Мы начнём с данных, которые опубликовал на Kaggle Ришабх Мисра — подробности по этой ссылке. Это действительно забавный общедоступный набор данных (под лицензией CC0), посвящённый выявлению сарказма. Правда? Да, правда! Этот набор данных очень простой, не говоря уже о том, что с ним очень просто работать. В нём три элемента. Первый — наша метка, is_sarcastic (сарказм ли это). Она равна единице, если в строке есть сарказм, в противном случае это 0. Вторая — headline (заголовок), это просто текст. А третья — это ссылка на статью, которая была опубликована под этим заголовком. Скачивание содержимого HTML-страниц, очистка от скриптов, стилей и т.п. — несколько выходит за рамки этого курса. Так что мы сосредоточимся только на заголовках. Если вы скачаете данные с сайта Kaggle, то увидите что-то вроде этого. Как видите, это список, каждый элемент которого содержит пары имя-значение с именами article_link, headline и is_sarcastic, а значения подобны тем, что на экране. Чтобы проще было загрузить данные в Python, я немного подправил данные, чтобы они выглядели примерно так. Вы можете поступить так же, или же просто скачать по ссылке мой изменённый набор данных в colab для работы с ними в этой части курса. Получив данные, похожие на эти, загрузить их в Python очень просто. Давайте посмотрим на код. Сначала вам нужно импортировать модуль json. Это позволит вам загружать данные в формате json и автоматически превращать их в структуры данных языка Python. Чтобы сделать это, просто откройте файл и передайте его в функцию json.load — и вы получите список, содержащий списки значений трёх типов: заголовки, URL-адреса и метки is_sarcastic. Поскольку я хочу получить предложения в виде списка, без лишней информации, чтобы передать их в токенизатор, я создаю список предложений, а позже, когда мне для построения нейросети понадобятся метки — я сделаю и список меток тоже. И раз уж я занялся этим, сделаю заодно и список URL, хотя я и не собираюсь их тут использовать, но вдруг вы захотите это сделать. Теперь я могу пройтись по созданному списку значений циклом "for item in datastore". Для каждого элемента я скопирую заголовок в список sentences, метку is_sarcastic — в список labels, а ссылку на статью — в список urls. Теперь у меня есть данные, которые можно обработать токенизатором, так что давайте на это посмотрим.

14(w1)-video11: Working with the Tokenizer (17.MLg_3c)

This code is very similar to what you saw in the earlier videos, but let's look at it line by line. We've just created a sentences list from the headlines, in the sarcasm data set. So by calling tokenizer.fit_on_texts, will generate the word index and we'll initialize the tokenizer. We can see the word index as before by calling the word index property. Note that this returns all words that the tokenizer saw when tokenizing the sentences. If you specify num words to get the top 1000 or whatever, you may be confused by seeing something greater than that here. It's an easy mistake to make, but the key thing to remember, is that when it takes the top 1000 or whatever you specified, it does that in the text to sequence this process. Our word index is much larger than with the previous example. So we'll see a greater variety of words in it. Here's a few. Now we'll create the sequences from the text, as well as padding them. Here's the code to do that. It's very similar to what you did earlier, and here's the output. First, I took the first headline in the data set and showed its output. We can see that it has been encoded with the values for the keys that are the corresponding word in the sentence. This is the size of the padded matrix. We had 26,709 sentences, and they were encoded with padding, to get them up to 40 words long which was the length of the longest one. You could truncate this if you like, but I'll keep it at 40. That's it for processing the Sarcasm data set. Let's take a look at that in action in a screen cast.
---------------------------------------------------------------
Этот код очень похож на тот, что вы видели в предыдущих видео, Но давайте рассмотрим его построчно. Мы только что создали список предложений из заголовков на наборе данных, посвящённом сарказму. Вызов функции tokenizer.fit_on_texts сгенерирует словарь и настроит токенизатор. Как и раньше, можно посмотреть получившийся словарь, обратившись к свойству word_index. Обратите внимание, что словаре содержатся все слова, которые токенизатор получил в списке предложений. Если задать значение параметра num_words=1000 или что-то в этом духе, вас может смутить то, что в word_index слов окажется больше. Здесь нетрудно ошибиться, но главное — запомнить, что когда токенизатор берёт наиболее часто встречающуюся тысячу слов (или сколько вы зададите) — то делает он это во время вызова функции text_to_sequences. [а не fit_on_texts - прим. пер.] Наш словарь намного больше, чем в предыдущем примере. Так что мы увидим в нём куда большее разнообразие слов. Вот некоторые из них. Далее мы делаем из текста последовательности и выравниваем их. Вот код, который это делает. Он очень похоже на то, что вы сделали раньше. А здесь вывод результатов. Сначала я взял первый заголовок из набора данных — и показал, во что он преобразован. Мы видим, что он закодирован значениями, которые соответствуют словам в предложении. А это размер дополненной матрицы. У нас 26 709 предложений, и они закодированы с выравниванием до длины в 40 слов, что является длиной самого длинного предложения. Вы можете уменьшить длину, если хотите, но я оставлю 40. Вот мы и обработали набор данных, посвящённый сарказму. Давайте посмотрим демонстрацию его работы.

15(w1)News headlines dataset for sarcasm detection: (17.MLg_3c)

The following is the public domain dataset based on sarcasm, as depicted in the previous video.
The link is provided here for your convenience:
Sarcasm in News Headlines Dataset by Rishabh Misra
https://www.kaggle.com/datasets/rmisra/news-headlines-dataset-for-sarcasm-detection
---------------------------------------------------------------
Ниже приведен общедоступный набор данных, основанный на сарказме, как показано в предыдущем видео.
Ссылка дана здесь для вашего удобства:
Сарказм в наборе данных заголовков новостей от Rishabh Misra
https://www.kaggle.com/datasets/rmisra/news-headlines-dataset-for-sarcasm-detection

16(w1)Check out the code! (Lab 3): (17.MLg_3c)

Ungraded Lab: Tokenizing the Sarcasm Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W1/ungraded_labs/C3_W1_Lab_3_sarcasm.ipynb

17(w1)-video12: Notebook for lesson 3 (17.MLg_3c)

Okay, so let's take a look at the code.
So the first thing I'm going to do is download the modified dataset. So I modified the dataset from Kaggle as I showed in the video to create this sarcasm.json.which just makes it a little bit easier for us to load in python.
So then I import JSON and by importing JSON that gives me access to this object that I can call json.load and it makes life really simple for me that I've downloaded my file, I've stored it in slash TMP slash sarcasm.json. And then I can say by opening that as F. I can create this list called data store by saying json dot load F. And now all the data has been loaded for me. For tokenizing I want to pull out the headlines in two sentences and later when we're using a neural network to classify them, I will create labels from those from the ratings within the dataset. So I may as well just take that out the ratings I'm calling what is sarcastic at zero or 1 and if you ever want to like explore the URLs. I'm not going to do that here. I can also just create a list of URLs and pull them out.
Then all I have to do is iterate across the data store that I just created and then for each item in the data store in my sentences list, I'm going to upend the headline to my labels list. I'm going to upend the sarcastic value and this will actually come out as an integer. So I don't need to do any casting or changing and from my URLs if I want them I can also append the article link. So now I have my sentences let's take a look at what it will take to tokenize them and the code for this should be very familiar by now. So I'm going to import tokenizer from tensorflow keras that pre processing dot text. I'm going to import pad sequences from tensorflow keras pre processing dot sequence. I'm going to specify my out of vocabulary token and then I'm just going to fit on texts with the sentences. So now the sentences is the entire corpus of headlines.
I can take a look at my word index and I'm going to print the length of that word index and there's something really important here that we can discuss. And then I'll print the word index itself. Then finally I'm going to create a set of sequences to encode the words from these sentences into the values where the word is that particular key. And then I'm going to pad that out. I'm just going to keep this at default except for the fact that I'm going to pad post. So on shorter sentences I want to have zeros at the end and then print them out. So let's run this and see what happens.
So we can see it's downloaded my sarcasm.json. It's printed in this case 29657 was the print of the length of the word index which we see here. So there were 29657 unique words in this corpus. And then print out my word and next and we can see my out of vocabulary was 12 is 2 office 3, there's 4, those kind of things. And I then take a look at my sequences, I'll generate my sequence, I'll generate my padded and then I print out the padding for the first sentence just so we can see it. We can see the first sentence only had a few words in it and it got padded out with a lot of zeros. And then we'll see the size of my padded matrix that's coming out. So that's 26,709 sentences that have been encoded Into 40 integers percentage. That suggests to me that the longest sentence in the corpus was 40 words. And for example, this one where it's a bit shorter. It's padded it out with zeros extra. If I wanted to truncate it, I could have done that in the pad sequences. Now, one important thing is this word index. So a lot of time when we say when you're creating the word when you're creating the tokenizer and you're fitting it on text. You could specify the maximum number of words that you want. This word index will always be the same regardless of the number that you set for your maximum. So for example, had I set for a 100 words maximum, the word index would still have 29657. It would only take into account the 100 when it's actually creating the sequences. And then it will take my top 100 words and words that aren't in those top 100, then it would replace with the out of vocabulary. So one important thing and I'm not going to cover it here. But one important thing if you're doing this for real later on is that you'll see there's a lot of words here, like to and off and the and in and for which are going to be in your top 100. So if you're going to be truncating to the top number of words, you might want to get rid of a lot of like meaningless words like these and then focus on the more important words, the ones that have semantics for you. And it would actually, I think the easiest way to do that would be to remove them from the sentences themselves before you fit on texts. And then you don't have to worry about those words ending up in the index. But it's entirely up to you.
So that's it for this one. We'll move on to your exercise for the week, next
---------------------------------------------------------------
Давайте же заглянем в код.
Первым делом скачаем изменённый набор данных. Я переработал набор с Kaggle, который демонстрировал в лекции, подготовив sarcasm.json, который чуть проще будет загрузить в Python.
Импорт модуля json обеспечивает доступ к объекту json, у которого можно вызвать метод load, сильно упрощающий мне жизнь. Я сохранил скачанный файл в ./tmp/sarcasm.json. И теперь могу написать open(...) as f и создать список datastore, вызвав json.load(f). Теперь все данные подгружены. Для разбиения на токены нужно вытянуть заголовки в список sentences, далее мы будем использовать для их классификации нейронную сеть, так что я создаю метки на основе оценок, взятых из набора данных. Их можно взять напрямую из данных, выбирая атрибут is_sarcastic, равный 0 или 1. А также, если хотите, можно взглянуть и на URL. Я здесь не буду этим заниматься. Просто создам ещё один список с url, куда их и буду извлекать.
Нужно лишь пройтись по только что созданному datastore и из каждого его элемента взять заголовок и добавить его в список предложений sentences, а в список меток добавить значение is_sarcastic, являющееся целым числом, так что преобразования типов не требуется. А если мне нужны URL, то их можно взять из article_link. Итак, предложения я получил. Посмотрим, что будет, если их разбить на токены. Код уже должен быть вам хорошо знаком. Я импортирую Tokenizer из tensorflow.keras.prerpocessing.text, А также импортирую pad_sequences из tensorflow.keras.prerpocessing.sequence, после чего создам токенизатор, задав ему токен OOV ("нет в словаре"), после чего вызову fit_on_text(sentences). В sentences хранится весь набор заголовков.
Можно посмотреть содержимое индекса слов — я выведу его длину, которая, как мы обсуждали, играет важную роль. Затем я выведу значение самого word_index. Наконец, создам ряд последовательностей, кодирующих слова из данных предложений значениями, хранящимися по ключам, соответствующим словам. А затем выполню их выравнивание. Я оставлю настройки по умолчанию, за исключением выбора дополнения в конец. Тогда у более коротких предложений нули будут добавляться в конец. Выведем результат. Давайте запустим код и посмотрим, что будет.
Видим, как скачивается файл sarcasm.json. В данном случае выводится число 29657 — это длина индекса слов word_index, выводимая в этой строке. У нас в корпусе текстов 29657 уникальных слов. Далее выводим содержимое word_index и видим, что у <OOV> значение 1, "to" — 2, "of" — 3, "the" — 4, и т.д. Далее смотрим, какие получились последовательности после применения выравнивания. Я вывожу выровненный вариант для первого предложения, чтобы посмотреть его. Видно, что в этом первом предложении слов было немного, и оно было дополнено большим числом нулей. Ниже мы видим получившийся размер выровненной матрицы. У нас 29657 предложений, и каждое кодируется 40 целыми числами. Это подсказывает мне, что в самом длинном предложении корпуса было 40 слов. А это, например, оказалось покороче и было дополнено нулями. Если бы мне хотелось уменьшить размерность, это тоже можно было задать в pad_sequences. Один важный момент связан с индексом слов. Очень часто при создании токенизатора и его настройке на заданном корпусе текстов стоит указывать максимальное число используемых слов. Но индекс слов всегда будет одинаковым, независимо от того, какой максимум вы зададите. Так, скажем, если я задам максимум в 100 слов, то индекс слов всё равно будет содержать 29657. Этот лимит в 100 слов повлияет только на создаваемые последовательности. Тогда будут взяты 100 самый частотных слов, а слова, не попавшие в этот топ-100, будут заменяться на токен "нет в словаре". Так что важный момент, который я здесь подробно не разбираю, состоит в том, что на реальных задачах в индексе вы увидите массу слов, таких как "to", "of", "the", "in", попадающих в топ-100. Так что если вы будете сокращать словарь, оставляя самые частотные слова, то может потребоваться избавиться от подобных слов, не несущих смысла, и сосредоточиться на более важных, более осмысленных в вашем случае словах. На мой взгляд, проще всего это сделать, удалив нежелательные слова из самих предложений, перед подачей текста на токенизатор. Тогда не нужно будет заботиться о попадании таких слов в индекс. Но тут вам решать.
На этом мы закончили. Нас ждёт упражнение следующей недели.

18(w1)- Week 1 Quiz: (17.MLg_3c)

1) What is the name of the object used to tokenize sentences?:
1. Word Tokenizer
2. Tokenizer (+)
3. TextTokenizer
4. Character Tokenizer
2)What is the name of the method used to tokenize a list of sentences?:
1. fit_on_texts(sentences) (+)
2. tokenize_on text(sentences)
3. fit_to text(sentences)
4. tokenize(sentences
3) Once you have the corpus tokenises, what's the method used to encode a list of sentences to use those tokens?:
1. texts_to_sequences(sentences) (+)
2. text_to_sequences(sentences)
3. text_to_tokens(sentences)
4. texts_to_tokens(sentences)
4) When initializing the tokenizer, how do you specify a token to use for unknown words?:
1. oov_token=<Token> (+)
2. unknown_work=<Token>
3. out_of_vocab=<Token>
4. unknown_token=<Token>
5) If you don't use a token for out of vocabulary words, what happens at encoding?:
1. The word isn't encoded, and the sequencing ends
2. The word isn't encode, and is replaced by a zero in the sequence
3. The word is replaced by the most common token
4. The word isn't encoded, and is skipped in the sequence (+)
6) If you have a number of sequences of different lengths, how do you ensure that hey are understood when fed into a neural network?:
1. Make sure that they are all the same length using the pad_sequences method of the tokenizer (-)
2. Use the pad_sequences function from the tensorflow.keras.preprocessing.sequence namespace (+)
3. Process them in the input layer of the Neural Network using the pad_sequences property
4. Specify the input layer of the Neural Network to expect different sizes with dynamic_length
7) If you have a number of sequences of different length, and call pad_sequences on them, that's the default result?:
1. Nothing, they'll remain unchanged
2. They'll get padded to the length of the longest sequence by adding zeros to the beginning of shorter ones (+)
3. They'll get cropped to the length of the shortest sequence
4. They'll get padded to the length of the longest sequence by adding zeros to the end of shorter ones (-)
8) When padding sequences, if you want the padding to be at the end of the sequence, how do you do it?:
1. Pass padding='after' to pad_sequences when initializing it
2. Pass padding='post' to pad_sequences when initializing it (+)
3. Call the padding method of the pad_sequences object, passing it 'after'
4. Call the padding method of the pad_sequences object, passing it 'post'

19(w1)-video13: Week 1 Wrap up (17.MLg_3c)

This week, you looked at how to tokenize words, turning them into numbers, and using a dictionary to look up which word goes with which number. Next week, you'll take that to the next step using something called Embeddings, that takes these numbers and starts to establish sentiment from them, so that you can begin to classify and then later predict texts.
---------------------------------------------------------------
На этой неделе вы посмотрели, как токенизировать слова, превращать их в числа и использовать словари, чтобы посмотреть, какое слово соответствует какому номеру. На следующей неделе вы перейдёте к следующему шагу — использованию сущности под названием эмбеддинг, которая берёт эти числа и начинает извлекать из них эмоции, позволяя сначала классифицировать, а затем и предсказывать тексты.

20(w1)-Lecture Notes Week 1: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/natural-language-processing-tensorflow/ungradedLti/jF6xb/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License. DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
ou may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/natural-language-processing-tensorflow/ungradedLti/jF6xb/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons. DeepLearning.AI делает эти слайды доступными для образовательных целей.
https://www.deeplearning.ai
Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
Остальные сведения о лицензии см.
https://creativecommons.org/licenses/by-sa/2.0/legalcode

21(w1)-Assignment Troubleshooting Tips: (17.MLg_3c)

Here are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
1. For assignments that use Coursera Labs instead of Google Colab: Make sure to save your work before clicking the Submit button. If not, you might get an error message like in the code cell below. Remember that everything that you need to fill in within the graded functions is initialized to None.
Failed test case: x has incorrect type.
Expected:
some.Type,
but got:
<class 'NoneType'>.
2. For assignments that use Coursera Labs instead of Google Colab: Please do not rename the notebook. The grader will look for the original filename and its associated metadata so you should work on the file that is automatically opened when you click the Launch Notebook button. If you try to submit a renamed notebook, then you will likely also get an error like the one shown above.
3. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
4. After following the tips above and the grader still gives you 0/100, it's possible that the metadata needed for grading is corrupted. Please get a new lab notebook by refreshing your workspace (
instructions here). Then copy your solutions into the new notebook. Make sure that all cells still run as expected then resubmit.
5. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by following the instructions here. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
---------------------------------------------------------------
Ниже приведены некоторые общие рекомендации перед отправкой заданий в рамках этого курса. Пожалуйста, имейте это в виду не только для задания этой недели, но и для следующих:
1. Для заданий, которые используют Coursera Labs вместо Google Colab: обязательно сохраните свою работу, прежде чем нажимать кнопку «Отправить». В противном случае вы можете получить сообщение об ошибке, как в ячейке кода ниже. Помните, что все, что вам нужно заполнить в оценочных функциях, инициализируется значением None.
Неудачный тестовый пример: x имеет неправильный тип.
Ожидал:
какой-то.Тип,
но получил:
<класс 'Неттип'>.
2. Для заданий, которые используют Coursera Labs вместо Google Colab: не переименовывайте блокнот. Оценщик будет искать исходное имя файла и связанные с ним метаданные, поэтому вам следует работать с файлом, который автоматически открывается при нажатии кнопки «Запустить блокнот». Если вы попытаетесь отправить переименованный блокнот, вы, вероятно, также получите сообщение об ошибке, подобное показанному выше.
3. Пожалуйста, не изменяйте код вне тегов START CODE HERE и END CODE HERE. Ваше решение должно быть размещено только между этими маркерами, чтобы гарантировать успешное оценивание. Изменение параметров функции и других тестовых ячеек, скорее всего, приведет к поломке оценщика. Если вы хотите поэкспериментировать с ними, вы можете сделать это после того, как успешно пройдете задание.
4. Если после выполнения приведенных выше советов оценщик по-прежнему выдает вам 0/100, возможно, метаданные, необходимые для оценивания, повреждены. Получите новую лабораторную тетрадь, обновив рабочее пространство (
инструкции здесь). Затем скопируйте свои решения в новый блокнот. Убедитесь, что все ячейки по-прежнему работают должным образом, а затем повторите отправку.
5. Если у вас есть дополнительные вопросы, создайте тему в сообществе Discourse, а не на дискуссионных форумах Coursera. Вы можете присоединиться, следуя инструкциям здесь. Вы получите помощь там быстрее, потому что несколько наставников и ваших однокурсников следят за сообщениями. Просто убедитесь, что тема создана в правильной категории курса.

22(w1)-Refreshing your Workspace: (17.MLg_3c)

Most assignments in this course use Coursera Labs to provide a notebook environment and to grade your work. There might be some instances where you want to download your notebooks or refresh your workspace to start from scratch. This reading item outlines the steps to do so.
Downloading your Notebook
In case you need to download your notebook for troubleshooting or running in your local environment, you can follow these simple steps:
From the Menu Bar of the notebook you are working on, Click File → Save and Checkpoint to first save your progress.
Click File → Download as → Notebook (.ipynb). This should start downloading the file into your local machine.
Refreshing your Workspace
This will come in handy whenever you need to start from scratch, fetch the latest version of the assignment, or run into a 404 error.
Open the notebook from the classroom.
After the notebook opens up, click File → Open
When your workspace opens, tick the check box before your notebook file. After it is selected, press Shutdown. The icon beside the filename should turn from green to gray.
Tick the checkbox again and this time choose Rename and enter any filename other than the original. For example, C4W1_Assignment.ipynb (original) → C4W1_Assignment_v2.ipynb
(Optional) Tick the checkbox of any other file that you want to get a fresh copy of (e.g. dataset files that you might have manipulated irreversibly). Then click Delete . You can also opt to Rename or Download each file individually in case you want to keep them before deleting.
Click on the Help button on the top right of the page.
Click the Get latest version button.
Click the Update Lab button. The page will refresh and you should now see the latest version of the notebook.

22(w1)-Programming Assignment: Explore the BBC news archive: (17.MLg_3c)

Week 1: Explore the BBC News archive
https://www.coursera.org/learn/natural-language-processing-tensorflow/programming/lI0HI/explore-the-bbc-news-archive/lab?path=%2Fnotebooks%2FC3W1_Assignment.ipynb

NEXT week_2 (17.MLg_3c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2)Word Embeddings (17.MLg_3c)

(Вложения слов)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video: 30 minutes
Self-study: 2h 27 min
Graded tasks (Tasks to be assessed): 2

(w2) Content (17.MLg_3c)

1. TFDS - TensorFlow Data Services
2. IMDB в машинном обучении означает разработку модели, которая может автоматически определять тональность отзывов на фильмы на основе набора данных IMDB Movie Review
3. (RNN) - это тип нейронной сети, специально разработанный для работы с последовательными данными, такими как временные ряды, тексты или аудио.
4.

(w2) Introduction: (17.MLg_3c)

Last week you saw how to use the Tokenizer to prepare your text to be used by a neural network by converting words into numeric tokens, and sequencing sentences from these tokens. This week you'll learn about Embeddings, where these tokens are mapped as vectors in a high dimension space. With Embeddings and labelled examples, these vectors can then be tuned so that words with similar meaning will have a similar direction in the vector space. This will begin the process of training a neural network to understand sentiment in text -- and you'll begin by looking at movie reviews, training a neural network on texts that are labelled 'positive' or 'negative' and determining which words in a sentence drive those meanings.
---------------------------------------------------------------
На прошлой неделе вы видели, как использовать Tokenizer для подготовки вашего текста к использованию нейронной сетью путем преобразования слов в числовые токены и создания последовательности предложений из этих токенов. На этой неделе вы узнаете о встраиваниях, где эти токены отображаются как векторы в пространстве высокой размерности. Затем с помощью Embeddings и помеченных примеров эти векторы можно настроить так, чтобы слова с похожим значением имели одинаковое направление в векторном пространстве. Это положит начало процессу обучения нейронной сети понимать настроение в тексте — и вы начнете с просмотра обзоров фильмов, обучения нейронной сети на текстах, помеченных как «положительные» или «отрицательные», и определения того, какие слова в тексте предложения управляют этими значениями.

1(w2)-video1: A conversation with Andrew Ng (17.MLg_3c)

Welcome back. In this week, you'll learn how to use the Keras layer in TensorFlow to implement word embeddings, which is one of the most important ideas in Natural Language Processing. If you have a vocabulary size of say 10,000 words, rather than using the numbers from 1-10,000 to represent these words, can you have a better way to represent those numbers? So this week you'll learn about word embeddings and also get to train your own neural network for text classification. It's really interesting that I really liked how embeddings work for representing the semantics of a word. So now instead of the word just being a number, it's like a vector in n-dimensional space. We're using 16 and 32 dimensions in different examples. So for example the word dog, might be a vector pointing in a particular direction and then the word "canine", could be learned as a vector pointing in a very similar direction, and we know they have very similar semantic meaning off of that. All of this is actually done for us in embeddings. So as we train like our datasets, we'll train for example with IMDB which is movie reviews, and there's a set of positive reviews and a set of negative reviews, and what will actually happen is the embeddings for the words in these reviews, and we can actually plot them on a chart. So we'll see something that looks like a globe and one of the poles on the globe or all the words that are clustered around for the positive review, and all the words on the other pole of the globe are clustered around the negative review, and it really helps us to start to see the semantics behind these words. I think one of the coolest things about word embedding is you can download the pretrained word embedding that maybe someone else has trained. This gives your learning algorithm a hint into the meaning of these words. So when you see another vocabulary word, maybe you see "canine" for the first time, it's as if you can let the algorithm know that "canine" means something a little bit like dog related to dog even if you've never seen the word "canine" in your specific training. That's amazing. Today in the world of applied NLP, word embeddings has proved to be one of the most powerful and useful ideas to help teams get good performance. So in this week, you'll learn how to use word embeddings in TensorFlow. Let's go on to the next video.
---------------------------------------------------------------
С возвращением! На этой неделе вы научитесь использовать слои Keras в TensorFlow для работы с эмбеддингами, а это одно из самых важных понятий в работе с естественными языками. Если у вас есть словарь объёмом, скажем, 10 000 слов, то не лучше ли будет вместо использования чисел от 1 до 10 000 для их представления — найти взамен более удобный способ? Итак, на этой неделе вы узнаете про эмбеддинги, а также натренируете собственную нейросеть для классификации текстов. Любопытно: мне очень нравится, как эмбеддинги работают с семантикой слова. Вместо того, чтобы заменять слово просто на номер, мы представляем его вектором в n-мерном пространстве. В разных примерах мы используем 16 и 32 измерения. Например, слово "собака" может быть вектором, указывающим в некотором направлении, и слово K9 тоже при обучении может стать вектором, указывающим в очень похожем направлении, и мы из этого можем понять, что их значения очень похожи. И всё это организуют для нас эмбеддинги. И подобно тому, как мы тренировались на наших наборах данных, мы натренируем модель, например, на кинорецензиях с IMDB, там есть набор положительных рецензий и набор отрицательных рецензий, и мы сможем сделать вот что: соответствующие словам из рецензий эмбеддинги мы отобразим на графике. И увидим нечто, похожее на глобус, и на одном из полюсов глобуса будут все слова, сосредоточенные в положительных рецензиях, а все слова другого полюса глобуса сосредоточены в отрицательных рецензиях, и это очень поможет нам разглядеть семантику за этими словами. Я думаю, самое крутое в эмбеддингах — то, что вы можете скачать заранее натренированный набор эмбеддингов для слов, который, возможно, натренировал кто-то другой. И это даст вашей модели подсказку насчёт значения этих слов. И встречая слово, которого нет в словаре, скажем, впервые встретив слово K9, то с помощью эмбеддингов можно дать знать алгоритму, что K9 означает нечто, похожее на собаку, связанное с собаками, даже если у вас слово K9 вообще не встречалось в тренировочном наборе данных. Это потрясающе. На данный момент в мире прикладной обработки естественных языков эмбеддинги закрепились как одна из наиболее мощных и полезных концепций, и они помогают получить высокие результаты. Итак, на этой неделе вы научитесь использовать эмбеддинги в TensorFlow. Давайте перейдем к следующему видео.

2(w2)-video2: Introduction (17.MLg_3c)

Last week, you looked at tokenizing text. Where turn text into sequences of numbers with a number was the value of a key value pair with the key being the word. So for example, you could represent the word TensorFlow with the value nine, and then replace every instance of the word with a nine in a sequence. Using tools and TensorFlow, you are able to process strings to get indices of all the words in a corpus of strings and then convert the strings into matrices of numbers. This is the start of getting sentiment out of your sentences. But right now, it's still just a string of numbers representing words. So from there, how would one actually get sentiment? Well, that's something that can be learned from a corpus of words in much the same way as features were extracted from images. This process is called embedding, with the idea being that words and associated words are clustered as vectors in a multi-dimensional space. Here, I'm showing an embedding projector with classifications of movie reviews. This week, you'll learn how to build that. The reviews are in two main categories; positive and negative. So together with the labels, TensorFlow was able to build these embeddings showing a clear clustering of words that are distinct to both of these review types. I can actually search for words to see which ones match a classification. So for example, if I search for boring, we can see that it lights up in one of the clusters and that associated words were clearly negative such as unwatchable. Similarly, if I search for a negative word like annoying, I'll find it along with annoyingly in the cluster that's clearly the negative reviews. Or if I search for fun, I'll find that fun and funny are positive, fundamental is neutral, and unfunny is of course, negative. This week, you'll learn how to use embeddings and how to build a classifier that gave that visualization. You're most of the way there already with the work that you've been doing with string tokenization. We'll get back to that later but first let's look at building the IMDB classification that you just visualized.
---------------------------------------------------------------
На прошлой неделе вы посмотрели, как токенизировать тексты. Мы превращали тексты в последовательности чисел, где числа были значениями в паре "ключ-значение", а ключами были сами слова. Например, вы могли представить слово TensorFlow числом 9, и затем заменить каждое вхождение этого слова в последовательности на число 9. Используя TensorFlow и другие инструменты вы можете обработать строку так, чтобы получить числа для всех слов из корпуса текстов, а затем превратить эти тексты в матрицу с числами. Это начало того процесса, который измерит эмоциональную окраску предложений. А пока это просто последовательность чисел, представляющих слова. Как же можно получить отсюда эмоции? Их можно извлечь из корпуса слов способом, очень похожим на тот, которым признаки извлекаются из изображений. Этот процесс называется эмбеддингом, он основывается на представлении о том, что слова группируются вместе с другими связанными словами в виде векторов многомерного пространства. Здесь я показываю проекцию эмбеддинга, получившегося из классификации кинорецензий. На этой неделе вы узнаете, как построить такой эмбеддинг. Рецензии делятся на два основных подвида: положительные и отрицательные. Обладая метками, TensorFlow оказался способен построить эти эмбеддинги, выявляя отчётливую группировку слов, которыми эти два типа рецензий отличаются друг от друга. Я могу поискать слова, чтобы увидеть те из них, которые определяют различия. Например, я ищу слово "скучно", и мы видим, что оно подсвечивается в одной из этих групп, и что соседние с ним слова — отчётливо негативные, например, "невозможно смотреть". Точно так же, если я поищу негативное слово, такое как "раздражающий", я найду его недалеко от слова "раздражает", в группе с явно отрицательными рецензиями. А если я поищу слово "забавно", я увижу, что слова "забавно" и "забавный" положительные, "Основательно" — нейтральное, и "не смешно" — конечно, отрицательное. На этой неделе вы научитесь использовать эмбеддинги и строить классификатор, который даёт такую визуализацию. Вы уже проделали большую часть пути по обучению токенизации текстов. Мы вернёмся к этому позже, но сперва давайте посмотрим как построить классификатор рецензий на IMDB, визуализацию которого вы сейчас видели.

3(w2)-video3: The IMDB dataset (17.MLg_3c)

Part of the vision of TensorFlow to make machine learning and deep learning easier to learn and easier to use, is the concept of having built-in data sets. You seen the little bit of a preview of the way back in the first course, when the fashion MNIST was available to you without you needing to download and split the data into training a test sets. Expanding on this, there's a library called TensorFlow Data Services or TFDS for short, and that contains many data sets and lots of different categories. Here's some examples; and while we can see that there are many different data sets for different types, particularly image-based, there's also a few for text, and we'll be using the IMDB reviews dataset next. This dataset is ideal because it contains a large body of texts, 50,000 movie reviews which are categorized as positive or negative. It was authored by Andrew Mass et al at Stanford, and you can learn more about it at this link.
---------------------------------------------------------------
Частью подхода TensorFlow к тому, как сделать машинное обучение и глубокое обучение легче в освоении и проще в использовании, — является то, что у него есть встроенные наборы данных. Вы уже немного знакомились с ними ещё в первом курсе, когда использовали предоставляемый набор данных с изображениями одежды, без необходимости его скачивать и делить на тестовый и тренировочный наборы данных. В дополнение к этому, есть библиотека под названием TensorFlow Data Services, сокращённо TFDS, и в ней есть много наборов данных в множестве различных категорий. Вот несколько примеров. И хотя мы видим здесь много различных наборов с данными разных типов, в т.ч., с изображениями, — здесь также есть несколько с текстами, и мы будем дальше использовать набор данных imdb_reviews. Этот набор данных идеален, потому что он содержит большой массив текстов — 50 000 кинорецензий, которые разделены на положительные и отрицательные. Его составил Эндрю Мас с коллегами из Стэнфорда, вы можете узнать больше подробностей по этой ссылке.

4(w2)-IMDB reviews dataset: (17.MLg_3c)

Please find the link to the IMDB reviews dataset here.
You will find here 50,000 movie reviews that are classified as positive or negative.
http://ai.stanford.edu/~amaas/data/sentiment/
---------------------------------------------------------------
Ссылку на набор данных отзывов IMDB можно найти здесь.
Здесь вы найдете 50 000 отзывов о фильмах, которые классифицируются как положительные или отрицательные.
http://ai.stanford.edu/~amaas/data/sentiment/

5(w2)-video4: Looking into the details (17.MLg_3c)

So let's start looking at it. There are a couple of things that you need to take into account before you start working with this week's code in TensorFlow. The first is the version of TensorFlow you're using. Use this code to determine it. Also, do note that all the code I'm using here is in Python 3. There are some differences if you use Python 2. So if you're using a Colab, you can set the environment to three. If you're doing this in your own environment, you may need to make some changes. Now, you can import TensorFlow datasets, and in this case I call them tfds. With imdb reviews, I can now call tfds.load, pass it the string imdb reviews, and it will return the data from imdb, and metadata about it with this code. The data is split into 25,000 samples for training and 25,000 samples for testing. I can split them out like this. Each of these are iterables containing the 25,000 respective sentences and labels as tensors. Up to this point, we've been using the Keras tokenizers and padding tools on arrays of sentences, so we need to do a little converting. We'll do it like this. First of all, let's define the lists containing the sentences and labels for both training and testing data. Now, I can iterate over training data extracting the sentences and the labels. The values are tensors, so by calling their NumPy method, I'll actually extract their value. Then I'll do the same for the test set. Here's an example of a review. I've truncated it to fit it on this slide, but you can see how it is stored as a tf.tensor. Similarly, here's a bunch of labels also stored as tensors. The value 1 indicates a positive review and zero a negative one. When training, my labels are expected to be NumPy arrays. So I'll turn the list of labels that I've just created into NumPy arrays with this code. Next up, we'll tokenize our sentences. Here's the code. I've put the hyperparameters at the top like this for the reason that it makes it easier to change and edit them, instead of phishing through function sequences for the literals and then changing those. Now, as before, we import the tokenizer and the pad sequences. We'll create an instance of tokenizer, giving it our vocab size and our desired out of vocabulary token. We'll now fit the tokenizer on our training set of data. Once we have our word index, we can now replace the strings containing the words with the token value we created for them. This will be the list called sequences. As before, the sentences will have variant length. So we'll pad and or truncate the sequenced sentences until they're all the same length, determined by the maxlength parameter. Then we'll do the same for the testing sequences. Note that the word index is words that are derived from the training set, so you should expect to see a lot more out of vocabulary tokens in the test exam. Now it's time to define our neural network. This should look very familiar by now, except for maybe this line, the embedding. This is the key to text sentiment analysis in TensorFlow, and this is where the magic really happens.
---------------------------------------------------------------
Итак, давайте посмотрим на этот набор [IDMB]. Есть пара моментов, которые следует принять во внимание, прежде чем начать работать с кодом этой недели для TensorFlow. Первый — какую версию TensorFlow вы используете. Запустите эти строки, чтобы это выяснить. Также обратите внимание, что весь код, который я использую здесь, написан на Python 3. Если у вас Python 2, будут некоторые различия. Так что, если вы используете Colab, то можете настроить окружение на использование 3-й версии. Если вы работаете в собственном окружении, то вам могут понадобиться некоторые изменения. Если предыдущий код показал, что у вас версия TensorFlow 1.x, нужно запустить эту строку прежде чем выполнять дальнейшие действия. Если же он показал версию 2.x, вам ничего не надо делать, т.к. TensorFlow 2.0 активирует "стремительное исполнение" по умолчанию. Если вы используете Google Colab, тогда у вас, скорее всего, уже установлены наборы данных из TensorFlow. Но даже если нет, они легко устанавливаются данной строчкой кода. Теперь можно импортировать наборы данных TensorFlow, в данном случае, я назову их tfds. Для того, чтобы загрузить imdb_reviews, я могу вызвать tfds.load и передать ему строку "imdb_reviews", и он вернёт данные с IMDB, и их метаданные как результат вызова функции. Данные разбиты на 25 000 записей для обучения и 25 000 для тестирования. Я могу разделить их, запустив такую строку. Через каждый из массивов можно пройти в цикле, они содержат по 25 000 предложений и меток в виде тензоров. До этого момента мы использовали токенизатор и инструмент для выравнивания массивов предложений из Keras, так что нам нужно слегка преобразовать данные. Мы сделаем это так. Во-первых, давайте определим списки, содержащие предложения и метки — как для тренировочного набора данных, так и для тестового. Теперь можно пройтись по всему тренировочному набору данных, извлекая из него предложения и метки. s и l имеют тип "тензор", так что вызывая их метод numpy(), я извлекаю их значения. Затем я сделаю то же самое с тестовым набором данных. Вот пример рецензии. Я обрезал его, чтобы он уместился на слайде, но вы можете посмотреть, как он хранится в тензоре. Аналогично, вот группа меток, сохранённых как тензоры. Значение 1 обозначает положительную рецензию, а 0 — отрицательную. При обучении модели у меток должен быть тип массивов numpy. Поэтому я преобразую только что созданные списки меток в массивы numpy с помощью данного кода. Затем мы токенизируем предложения. Вот соответствующий код. Я вынес все гиперпараметры в одно место в начале, чтобы было легче менять и редактировать их, вместо того, чтобы продираться через последовательность функций в поисках конкретных значений, и затем менять их. Тут, как и раньше, мы импортируем tokenizer и pad_sequences. Мы создадим токенизатор, передадим ему размер словаря и токен, который мы хотим указать в качестве "нет_в_словаре". Теперь обучаем токенизатор на тренировочном наборе данных. Получив наш словарь с токенами, мы можем теперь заменить содержащие слова строки на полученные значения токенов, и поместить их в список под названием sequences. Как и раньше, предложения будут разной длины. Так что мы дополним или обрежем предложения, преобразованные в последовательности, пока они не окажутся одной длины, указанной в параметре max_length. Затем мы сделаем то же самое для тестовых последовательностей. Обратите внимание, что в словарь входят только слова из тренировочного набора, так что в тестовых последовательностях стоит ожидать большего числа токенов OOV. Теперь пора определить структуру нашей нейросети. К этому моменту вам уже всё должно быть знакомо. Кроме, возможно, первого пункта — Embedding. Это ключевой элемент анализа эмоций в текстах при помощи TensorFlow, и именно тут происходит настоящая магия.

6(w2)-video5: How can we use vectors? (17.MLg_3c)

The full scope of how embeddings work is beyond the scope of this course. But think of it like this. You have words in a sentence and often words that have similar meanings are close to each other. So in a movie review, it might say that the movie was dull and boring, or it might say that it was fun and exciting. So what if you could pick a vector in a higher-dimensional space say 16 dimensions, and words that are found together are given similar vectors. Then over time, words can begin to cluster together. The meaning of the words can come from the labeling of the dataset. So in this case, we say a negative review and the words dull and boring show up a lot in the negative review so that they have similar sentiments, and they are close to each other in the sentence. Thus their vectors will be similar. As the neural network trains, it can then learn these vectors associating them with the labels to come up with what's called an embedding i.e., the vectors for each word with their associated sentiment. The results of the embedding will be a 2D array with the length of the sentence and the embedding dimension for example 16 as its size. So we need to flatten it out in much the same way as we needed to flatten out our images. We then feed that into a dense neural network to do the classification. Often in natural language processing, a different layer type than a flatten is used, and this is a global average pooling 1D. The reason for this is the size of the output vector being fed into the Dense. So for example, if I show the summary of the model with the flatten that we just saw, it will look like this. Or alternatively, you can use a Global Average Pooling 1D like this, which averages across the vector to flatten it out. Your model summary should look like this, which is simpler and should be a little faster. Try it for yourself in colab and check the results. Over 10 epochs with global average pooling, I got an accuracy of 0.9664 on training and 0.8187 on test, taking about 6.2 seconds per epoch. With flatten, my accuracy was 1.0 and my validation about 0.83 taking about 6.5 seconds per epoch. So it was a little slower, but a bit more accurate. Try them both out, and experiment where the results for yourself.
---------------------------------------------------------------
Полный охват работы эмбеддингов выходит за рамки этого курса. Но думайте о них примерно так. У вас есть слова в предложении, и часто слова с похожими значениями стоят близко друг к другу. Так, в кинорецензии может говориться, что кино было скучным и унылым, или что оно было увлекательным и захватывающим. И можно взять вектор в многомерном пространстве — 16-мерном, например, то словам, стоящим в тексте рядом, можно назначить близкие вектора. Тогда со временем слова могут начать группироваться вместе. Значение слов может исходить из меток этого набора данных. В нашем случае, можно сказать, что в отрицательной рецензии слова "унылый" и "скучный" появляются часто, так что они выражают близкие эмоции, и они стоят близко друг к другу в предложении. Так что их векторы будут похожими. И по мере обучения нейросети, она может запомнить эти векторы и связать их с метками, получив то, что называется эмбеддингами, т. е. с вектора для каждого слова вместе со связанными с ними эмоциями. Результатом эмбеддинга будет двухмерный массив, чья длина совпадает с длиной предложения, а размерность эмбеддинга — будет, например, 16. Нужно сделать массив одномерным, так же, как мы делали с изображениями. Затем мы передаём результат в полносвязную нейросеть для классификации. Часто в обработке естественных языков вместо слоя flatten используется другой способ, а именно, глобальное усреднение по одной оси. Так делают, чтобы уменьшить размер вектора, который попадает в плотный слой, Например, если я покажу сводку по модели со слоем flatten, код которой мы видели, то она будет выглядеть так. Если мы взаме используем слой GlobalAveragePooling1D, как здесь, который усредняет поперёк вектора, чтобы сделать массив одномерным, то сводка по модели будет выглядеть так — что делает модель проще и должно работать побыстрее. Попробуйте сами в Colab и сравните результаты. Обучая в течение 10 эпох с усреднением, я получил точность 0.9664 на тренировочном наборе и 0.8187 на тестовом, и это заняло около 6.2 секунд на эпоху. С развёртыванием вектора (flatten) точность была 1.0, а на тестовом наборе данных — около 0.83, и около 6.5 секунд на эпоху. Так что стало чуть медленнее, но и чуть точнее. Попробуйте оба варианта и самостоятельно поэкспериментируйте с результатами.

6(w2)-video5: More into the details (17.MLg_3c)

You can compile your model as before, and print out the summary with this code. Now training is as simple as passing padded and your training labels final as your training set, specifying the number of epochs, and passing the testing padded and testing labels final as your test set. Here's the results of training, with the training set giving us 1.00 accuracy and the validation set at 0.8259. So there's a good chance that we're overfitting. We'll look at some strategies to avoid this later, but you should expect results a little bit like this. Okay. Now we need to talk about and demonstrate the embeddings, so you can visualize them like you did right back at the beginning of this lesson. We'll start by getting the results of the embeddings layer, which is layer zero. We can get the weights, and print out their shape like this. We can see that this is a 10,000 by 16 array, we have 10,000 words in our corpus, and we're working in a 16 dimensional array, so our embedding will have that shape. To be able to plot it, we need to reverse our word index. As it currently stands, our word index has the key being the word, and the value being the token for the word. We'll need to flip this around, to look through the padded list to decode the tokens back into the words, so we've written this function. Now it's time to write the vectors and their metadata auto files. The TensorFlow Projector reads this file type and uses it to plot the vectors in 3D space so we can visualize them. To the vectors file, we simply write out the value of each of the items in the array of embeddings, i.e, the co-efficient of each dimension on the vector for this word. To the metadata array, we just write out the words. If you're working in Colab, this code will download the two files. To now render the results, go to the TensorFlow Embedding Projector on projector.tensorflow.org, press the ''Load data'' button on the left. You'll see a dialog asking you to load data from your computer. Use vector.TSV for the first one, and meta.TSV for the second. Once they're loaded, you should see something like this. Click this ''sphereize data'' checkbox on the top left, and you'll see the binary clustering of the data. Experiment by searching for words, or clicking on the blue dots in the chart that represent words. Above all, have some fun with it. Next up, we'll step through a screencast of what you've just seen, so you can explore it in action. After that, you'll look at how TFDS has built in tokenizers that prevent you from writing a lot of the tokenizing code that we've just used.
---------------------------------------------------------------
Выполнив данный код, можно скомпилировать модель, как мы уже делали, и вывести сводку. Обучать проще простого: передаём списки padded и training_labels_final в качестве обучающей выборки, указываем количество эпох и передаём testing_padded и testing_labels_final в качестве валидационной выборки. Вот результаты обучения. На обучающей выборке точность получается 1.0, а на валидационной — 0.8259. Это говорит о том, что есть большая вероятность переобучения. Позже мы обсудим несколько стратегий, как его избежать, а пока стоит рассчитывать, что результаты будут похожи на эти. А сейчас нам надо обсудить и продемонстрировать эмбеддинги, чтобы вы могли их визуализировать, как это было в начале этого урока. Мы начнём с получения результатов слоя embeddings, т.е., слоя с индексом 0. Можно получить его веса и вывести их размерность, как здесь. Мы видим, что это матрица 10 000 на 16: в нашем корпусе 10 000 слов, и мы работаем с 16-мерным массивом, поэтому наши эмбеддинги приобрели такую форму. Чтобы их вывести на график, нам нужна вспомогательная функция, которая обращает индекс слов. Сейчас в нашем индексе слов ключом служит само слово, а значением — его токен. Нам нужно поменять их местами, чтобы в списке выровненных последовательностей заменять токены обратно на слова. Так что мы написали вот такую вспомогательную функцию. Теперь выведем векторы и метаданные в результирующие файлы. Утилита Projector в составе TensorFlow прочитает файлы данного типа и использует их, чтобы отобразить векторы в трёхмерном пространстве, так что мы сможем их визуализировать. В файл векторов мы просто запишем значение каждого из элементов массива эмбеддингов, т. е., коэффициенты всех измерений вектора для этого слова. А в массив метаданных мы просто запишем слова. Если вы работаете в Colab, то данный код скачает два файла. Чтобы теперь отобразить результаты, откройте TensorFlow Embedding Projector на projector.tensorflow.org, нажмите на кнопку Load data слева, и вы увидите диалог, предлагающий загрузить данные с вашего компьютера. Выберите в первом поле файл vector.tsv, а во втором — meta.tsv. Когда они загрузятся, вы должны увидеть что-то похожее на это. Поставьте галочку "Sphereize data" слева вверху, и вы увидите разбиение данных на два кластера. Попробуйте искать здесь слова или покликайте на голубые точки на графике, которые представляют слова. Словом, поиграйте с графиком. Далее мы пошагово пройдёмся по коду, делающему то, что вы только что видели, чтобы вы могли изучить код в действии. После этого мы разберём встроенный в TFDS токенизатор, позволяющий не писать массу того кода для токенизации, что мы только что использовали.

7(w2)-Check out the code! (Lab 1): (17.MLg_3c)

Ungraded Lab: Training a binary classifier with the IMDB Reviews Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W2/ungraded_labs/C3_W2_Lab_1_imdb.ipynb

8(w2)-video6: Notebook for lesson 1 (17.MLg_3c)

Okay so let's take a look at the code, that we're going to use in this environment. So the next thing I'm going to do is just import TensorFlow datasets as TFDS. On TFDS load, IMDb reviews will give me an IMDb set and an info set. I'm going to use the info set in another video, we're not going to use it here. But the IMDb set is what we're going to be looking at here. So next up is the code where I'm going to get my IMDb training and my IMDb testing and load them into training and test data. I'm going to create lists of training sentences and labels, testing sentences and labels, and I'm going to copy the contents of the tensors into these so that I can encode and pad them later. So this code will just do that. Secondly also for training, I need numpy arrays instead of just straight array. So I'm going to convert my training labels that I created into a numpy array like this. So that's all done. So next up is where I'm going to do my sentence encoding. So I've decided I'm going to do a 10,000-word vocab size. Of course you can change that. My embedding dimensions, which you'll see in a moment will be 16 dimensions. I'm going to make sure all of my reviews are 120 words long. So if they are shorter than that there'll be padded. If there longer than that they'll be truncated. I'm setting the truncation type to be post, so we'll cut off the back of the review and not the front, and then my outer vocabulary token will be OOV like this.
So now if I import my TensorFlow keras preprocessing tokenizer, and pad sequences is in sequence as before. I'll instantiate my tokenizer passing it my vocabulary size, which as I said here earlier on was 10,000. Of course you can change that. Then my outer vocabulary token, the tokenizer will then be fit on the training sentences, not the testing sentences just the training ones. If I want to look at the word index for the tokenizer, all have to do say tokenizer.word_index. I will then convert my sentences into sequences of numbers, with the number being the value and the word being the key that were taken out of the training sentences when I did fit on text, and that will give me now my list of integers per sentence. If I want to pad or truncate them I use pads sequences to do that. So each of my sentences is now a list of numbers. Again, those numbers are the values in a key value pair, where the key of course is the word. The pad sequences will ensure that they're all the same length, which in this case is 120 words or 120 numbers. There'll be padded out or truncated to suit. I'm then going to do the same with the testing sequences, and I'm going to pad them in the same way. Do note that the testing sequences are tokenized based on the word index that was learned from the training words. So you may find a lot more OOVs, in the testing sequence than you would have in the training sequence, because there'll be a lot of words that it hasn't encountered. But that's what makes it a good test, because later if you're going to try out a review, you want to be able to do it to see how it will do with words that the tokenizer or the neural network hasn't previously seen. So I'll now run this code. I'll create my sequences, my padded sequences, my testing sequences, my testing patterns. This will take a few moments. So let's now take a look at the neural network itself, and it's very simple. It's just a sequential. The top layer of this is going to be an embedding, the embedding is going to be my vocab size, the embedding dimensions that I wanted to use, I had specified 16. My input length for that is 120, which is the maximum length of the reviews. So the output of the embedding will then be flattened, that will then be passed into a dense layer, which is six neurons and then that will be passed to a final layer with a sigmoid activation and only one neuron, because I know I've only got two classes. I'm just going to do one neuron instead of two. I didn't need to hard encode. I'll just do one neuron and my activation function being a sigmoid, it will push it to zero or one respectively. I can then compile that and take a look at the summary. Here's the summary, it all looks good. Again, each of my sentences, 120 characters, my embedding has 16, and out of that the flattened thing we'll have 1,920 values. They get fed into the dense. They get fed into the output layer. So let's train it. So I'm going to set just for 10 epochs and I'm going to fit it. So it's training, it's correct, 25,000 samples and validating on 25,000 samples. Let's see it training. Our accuracy starts at 73 percent on the training set, 85 on validation. Training over time is going to go up nicely. We're most likely overfitting on this, because our accuracy is so high, but even that a validation accuracy is not bad. It's in the 80s.
So we can see even by epoch seven our accuracy up to a one. Our validation accuracy is still in the low 80s, 81, 82 percent. Pretty good, but this clear overfitting going on. So by the time I've reached my final epoch, my training accuracy was 100 percent, my validation accuracy at 83 percent. It's quite healthy but I'm sure we could do better. So now let's take a look at what we'll do to view this in the embedding projector. So first of all, I'm going to take the output of my embedding, which was modeled out layer zero, and we can see that there were 10,000 possible words and I had 16 dimensions. Here is where I'm going to iterate through that array to pull out the 16 dimensions, the values for the 16 dimensions per word and write that as out_V, which is my vectors.tsv. Then the actual word associated with that will be written to out_M, which is my meta.tsv. So if I run that, it we'll do its trick and if you're running in Colab this piece of code, will then allow me to just download those files. So it'll take a moment and they'll get downloaded. There they are, vecs.tsv and meta.tsv. So if I now come over to the embedding projector, we see its showing right now the Word2Vec 10K. So if I scroll down here and say load data, I'll choose file, I'll take the vecs.tsv. I'll choose file. I'll take the meta.tsv, then load. I click outside and now I see this. But if I spherize the data, you can see it's clustered like this. We do need to improve it a little bit but we can begin to see that the words have been clustered in both the positive and negative. So for example if I search for the word boring, we can see like the nearest neighbors for boring are things like stink or unlikeable, prom, unrealistic wooden, devoid, unwatchable, and proverbial. So if come over here we can see. These are bad words. These are words showing a negative looking review.
I can see, there's lots of words that have fun in them, some positive, some negative, like unfunny, dysfunction, funeral are quite negative. So let's try exciting. So now if I come over here we're beginning to see, hey there's a lot of words clustered around positive, movies that matching exciting, that type of thing. So we can see them over really on this left-hand side of the diagram. Again, I just maybe if I search for Oscar, nothing really associated with Oscar because it's such a unique word. We could just have all kinds of fun with it like that. What if I search for brilliant? Again we can begin to see like words clustering over on this side, but there's not a lot of words that became close to brilliant. In this case, guardian, Jeffrey, Kidman, Gershwin. So these are brilliant being used as an adjective. Some good stuff in there though. So hopefully this is a good example of how you can start mapping words into vector spaces, and how you can start looking at sentiment and even visualizing how your model has learned sentiment from these sets of words. In the next video, we're going to look at a simpler version of doing IMDb than this one where we're doing writing a lot less code, we're taking advantage of stuff that was available to us TenserFlow data services.
---------------------------------------------------------------
Хорошо, давайте посмотрим на код, который мы будем использовать в этом окружении. Итак, если вы собираетесь использовать это пособие, пожалуйста, убедитесь, что установлен Python3. Для этого идём сюда и выбираем пункт Change runtime type и проверяем, что там стоит Python 3. Я оставляю аппаратное ускорение с GPU, чтобы увеличить скорость расчётов. Если импортировать TensorFlow под псевдонимом tf, и вывести значение tf.__version__, то вы увидите версию TensorFlow. Если вы проходите курс спустя время, то она может быть и 2.0. Если она 2.0, вам не нужно активировать стремительное исполнение, но поскольку тут версия 1.13, я подключу стремительное исполнение. И если у вас не установлены наборы данных TensorFlow, эта строка установит их вам, но у меня они уже установлены. Итак, дальше я просто импортирую наборы данных TensorFlow под псевдонимом tfds и загружаю с помощью функции tfds.load набор imdb_reviews, что даёт мне наборы данных imdb и info. Я собираюсь использовать info в другом видео, здесь же мы его использовать не будем. А вот с набором imdb мы поработаем прямо сейчас. Дальше идёт код, где я извлекаю тренировочный и тестовый наборы данных в переменные train_data и test_data. Я создам списки для тренировочных фраз и меток, а также для тестовых фраз и меток, и скопирую сюда содержимое тензоров, чтобы затем их закодировать и выполнить выравнивание. Итак, данный код всё это делает. Во-вторых, для обучения мне нужны массивы numpy вместо простых массивов, так что я преобразую созданные training_labels в массив numpy, вот так. Готово. Дальше я закодирую мои предложения. Я решил, что мне хватит словаря размером в 10 000 слов. Разумеется, вы можете изменить размер. Моих эмбеддинги, как вы сейчас увидите, будут 16-мерными. Я хочу обеспечить, чтобы все рецензии были длиной в 120 слов. Если они окажутся короче, то будут дополнены. Если длиннее — обрезаны. Я устанавливаю тип обрезки 'post', так что обрезка будет с конца рецензии, а не с начала, а мой токен для слов вне словаря будет <OOV>, как здесь.
Я импортирую из TensorFlow токенизатор и pad_sequences, как и раньше. Я инициализирую токенизатор, передавая ему мой размер словаря, который, как я уже сказал, равен 10 000. Конечно, вы можете его изменить. А также передаю токен для слов вне словаря. Токенизатор обучается на тренировочных предложениях — не на тестовых, а только на тренировочных. Если я хочу посмотреть на список слов токенизатора, нужно вызвать tokenizer.word_index. Затем я конвертирую мои предложения в последовательности чисел, где числа — это значения, а слова — ключи, взятые из тренировочных предложений, когда я запустил fit_on_texts. И тогда я получаю для каждого предложения по списку целых чисел. Если я хочу дополнить или обрезать их, то вызываю для этого функцию pad_sequences. Итак, каждое из моих предложений теперь стало списком чисел. Повторюсь, эти числа — значения в парах ключ-значение, где ключ, разумеется, это само слово. pad_sequences сделает их все одинаковой длины, в данном случае, это 120 слов, или 120 чисел. Они будут дополнены или обрезаны, чтобы удовлетворить ограничению. Затем я сделаю то же самое с тестовыми последовательностями, точно также выравнивая их. Обратите внимание, что тестовые последовательности токенизируются с использованием словаря, построенного на тренировочных словах, так что в тестовых последовательностях может встречаться куда больше токенов <OOV>, чем было в тренировочных, т.к. здесь будет множество слов, которые там не встречались. Но так даже лучше для проверки, ведь если вы захотите проверить какое-нибудь ревью, то нужно смотреть, как всё будет работать со словами, которые токенизатор или нейронная сеть раньше не видели. Итак, я запускаю этот код. Он создаёт мои последовательности, выровненные последовательности, тестовые последовательности и тестовые выровненные последовательности. Это займёт некоторое время. И теперь можно посмотреть, что выходит, запустив этот кусок кода. Например, тут вы видите, что я взял мой обратный индекс слов, и могу декодировать рецензию, поглядев на числа для этой рецензии и обратив их в слова. Итак, берём ключ для этого значения, и обратный индекс слов меняет местами ключ и значение. Мы видим, что декодированная рецензия, то, что пойдёт на вход [нейросети], это: "Я смотрел этот фильм на True Movies*, [*британский бесплатный телеканал - прим. пер.] что автоматически настроило меня <слово не из словаря>" — а в изначальком тексте, как видите, встречаются заглавные буквы, знаки препинания: скобки и запятые, — а слово "скептически" в результате не попало в 1000 использованных. Итак, это просто удобный способ, какого рода данные мы скормим нейросети. Давайте посмотрим теперь на саму нейросеть. Она очень простая. Слои идут последоветельно (Sequential): верхний слой — эмбеддинг, он будет по размеру моего словаря, а нужную мне размерность векторов эмбеддинга я задал равной 16. Длина входных данных у меня 120 — это максимальная длина рецензии. Вывод эмбеддинга надо сделать одномерным, затем он попадает в полносвязный слой с шестью нейронами, а их выход передаётся в последний слой с сигмоидным активатором и всего одним нейроном, ведь у меня всего два класса. И я буду использовать один нейрон, а не два, чтобы не приходилось менять код. Я делаю лишь один нейрон, и мой активатор будет сигмоидой, он будет прижимать выходные значения к 0 или 1. Теперь можно скомпилировать сеть и посмотреть сводку. Вот она, всё выглядит хорошо. Ещё раз: каждое из моих предложений состоит из 120 символов, размерность эмбеддинга 16, из выхода эмбеддингов делаем массив одномерным, это будет 1920 значений. Они попадают в полносвязный слой, а потом в выходной слой. Давайте обучим сеть. Я установлю всего 10 эпох и запущу fit. Сеть обучается, тут всё верно: 25 000 образцов и валидация на 25 000 образцов. Давайте посмотрим, как сеть обучается. Наша точность изначально 73% на тренировочных данных и 85% на валидационных. Точность на тренировочных данных со временем хорошо растёт. Мы здесь, похоже, переобучаемся, потому что наша точность столь высока, но даже при этом валидационная точность неплоха. Она больше 80%.
И мы видим, что уже к седьмой эпохе наша точность достигла 1.0. Наша валидационная точность всё ещё чуть выше 80%, 81-82%. Неплохо, но сеть явно переобучается. Итак, по завершении последней эпохи тренировочная точность 100%, а валидационная точность 82.35%. Это довольно неплохое значение, но я уверен, что может быть лучше. Теперь давайте посмотрим, как посмотреть результат в Embedding Projector. Во-первых, я извлекаю выход со слоя эмбеддинга, этот слой в модели был с индексом 0. И мы видим, что было 10 000 возможных слов и 16 измерений. Здесь я прохожу в цикле по массиву, чтобы извлечь эти 16 измерений, т.е., значения этих 16 измерений для каждого слова, и записать их в файл (переменная out_v) с именем vecs.tsv. А также само слово, связанное с эмбеддингом, записывается в out_m — файл с именем meta.tsv. Итак, если я это запущу, если сделать такой приём, и запустить в Colab этот участок кода, то смогу подгрузить сюда эти файлы. Нужно немного подождать — и вот они скачались. Вот они, vesc.tsv и meta.tsv. Если перейти к Embedding Projector, мы видим, что он показывает 10 000 слов из Word2Vec. Если прокрутить вниз и нажать на кнопку загрузки данных (Load data), выбрать файл — я возьму vecs.tsv, и выбрать ещё файл, я возьму meta.tsv — то файлы подгружаются. Кликну за пределами диалога, мы увидим вот это. Но если я отмечу Sphereize data, вы увидите, что они группируются вот так. Нам ещё требуются улучшения, но уже становится заметно, что слова группируются — как позитивные, так и негативные. Например, если найти слово boring [скучный], то мы видим его ближайших соседей, для "скучный" это слова вроде "отвратительный" или "непривлекательный", "ученический", "нереалистичный", "деревянный", "пустое место", "невозможно смотреть", "пресловутый". А если я пойду сюда, то мы увидим, что это плохие слова. Это слова, указывающие на отрицательную рецензию.
И видно, что здесь есть множество слов, можно поразвлекаться, их изучая: некоторые положительные, некоторые отрицательные, например: "не смешно", "неполноценный", "похоронный" — довольно отрицательные. Давайте попробуем "восхитительно". Если я перейду сюда, мы увидим — ого, здесь множество слов, сгруппированных вокруг положительно оцениваемых фильмов, получивших оценку "восхитительно" и ей подобные. Мы можем осмотреть их на левой стороне диаграммы. И давайте я попробую поискать "Оскар". С ним особо ничего не связано, ведь Оскар — крайне редкое здесь слово. Можно всячески играться с этими данными в том же духе. Что, если я поищу "блестящий"? И снова мы видим, что слова собираются на этой стороне, но не так уж много слов близки к слову "блестящий". В данном случае, это Гардиан, Джеффри, Кидман, Гершвин. "Блестящий" используется как определение. Тут всякие хорошие вещи. Я надеюсь, это хороший пример того, как можно отображать слова в векторное пространство и начинать искать эмоции, и даже визуализировать то, как ваша модель учится узнавать эмоции по набору слов. В следующем видео мы посмотрим на более простой способ работы с IMDB, чем этот — там наш код станет компактнее, т.к. мы воспользуемся тем, что предоставляют нам возможности TensorFlow Data Services.

9(w2)-video7: Remember the sarcasm dataset? (17.MLg_3c)

So that was an example using the IMDB data set, where data is provided to you by the tfds API, which I hope you found helpful. Now I'd like to return to the sarcasm data set from last week, and let's look at building a classifier for that. We'll start with importing tensorflow and json, as well as the tokenizer and pad sequences from pre-processing. Now let's set up our hyper parameters; the vocabulary size, embedding dimensions, maximum length of sentences, and other stuff like the training size. This data set has about 27,000 records. So let's train on 20,000 and validate on the rest. The sarcasm data is stored at this URL, so you can download it to /tmp/sarcasm.json with this code. Now that you have the data set, you can open it and load it as an iterable with this code. You can create an array for sentences, and another for labels, and then iterate through the datastore, loading each headline as a sentence, and each is_sarcastic field, as your label.
---------------------------------------------------------------
Итак, это был пример использования набора данных IMDB, где вы брали данные с помощью интерфейса TFDS, который, надеюсь, вы нашли для себя полезным. Сейчас я бы хотел вернуться к набору данных прошлой недели, который был посвящён сарказму. Давайте посмотрим, как построить классификатор для него. Начнём с импорта tensorflow и json, а также токенизатора и pad_sequences из библиотеки предварительной обработки. Теперь установим гиперпараметры: размер словаря, размерность эмбеддинга, максимальную длину предложений, и прочее, например, размер обучающей выборки. В этом наборе данных есть около 27 000 записей. Так что давайте обучать на 20 000 и тестировать на остальных. Набор данных находится по этому адресу, вы можете скачать его в файл /tmp/sarcasm.json, запустив этот код. Теперь, когда у вас есть набор данных, можно открыть и загрузить его в массив с помощью данного кода. Вы можете создать один массив для предложений и другой для меток, а затем циклом пройти по данным из datastore, загружая каждый заголовок как предложение, и каждое значение поля is_sarcastic в качестве метки.

10(w2)-video8: Building a classifier for the sarcasm dataset (17.MLg_3c)

To split the corpus into training and validation sets, we'll use this code. To get the training set, you take array items from zero to the training size, and to get the testing set, you can go from training size to the end of the array with code like this. To get the training and testing labels, you'll use similar codes to slice the labels array. Now that we have training and test sets of sequences and labels, it's time to sequence them. To pad those sequences, you'll do that with this code. You start with a tokenizer, passing it the number of words you want to tokenize on and the desired out of vocabulary token. Then fit that on the training set by calling fit on texts, passing it the training sentences array. Then you can use text to sequences to create the training sequence, replacing the words with their tokens. Then you can pad the training sequences to the desired length or truncate if they're too long. Next, you'll do the same but with a test set. Now, we can create our neural network in the usual way. We'll compile it with binary cross entropy, as we're classifying to different classes. When we call a model's summary, we'll see that it looks like this, pretty much as we'd expect. It's pretty simple and embedding feeds into an average pooling, which then feeds our DNN. To train for 30 epochs, you pass in the padded data and labels. If you want to validate, you'll give the testing padded and labels to. After training for little while, you can plot the results. Here's the code for simple plot. We can see accuracy increase nicely as we trained and the validation accuracy was okay, but not great. What's interesting is the loss values on the right, the training loss fall, but the validation loss increased. Well, why might that be?
---------------------------------------------------------------
Чтобы разделить корпус на тренировочный и валидационный наборы, мы используем данный код. Чтобы получить тренировочный набор, возьмём элементы массива от 0 до training_size, а чтобы получить тестовый набор, берём начиная с training_size и до конца массива с помощью такого кода. Чтобы получить метки для тестового и тренировочного наборов данных, массив меток labels разделяется аналогично. Теперь у нас есть тренировочный и тестовый наборы предложений и меток, и пора превратить их в последовательности и выполнить выравнивание этих последовательностей, что делается вот этим кодом. Вы начинаете с токенизации: передаёте количество слов, которые нужно токенизировать, а также желаемый токен "нет в словаре". Затем обучаете токенизатор на тренировочном наборе, вызывая метод fit_on_texts и передавая ему массив тренировочных последовательностей. Затем вы используете text_to_sequences, чтобы создать тренировочные последовательности, заменяя слова их токенами. Затем можно дополнить тренировочные последовательности до желаемой длины — или обрезать слишком длинные. Потом вы делаете то же самое с тестовым набором. Теперь можно создать нейросеть, как обычно. Мы скомпилируем её с функцией потерь 'binary_crossentropy', т.к. мы классифицируем на два разных класса. Если вывести сводку по данной сети, то она будет выглядеть вот так. Этого мы и ожидали. Сеть довольно простая, и данные из эмбеддинга попадают в усредняющий слой, который потом передаёт данные в полносвязную нейросеть. Чтобы тренировать в течение 30 эпох, вы передаёте выровненные данные и метки к ним. Если вы хотите проверять метрики на тестовом наборе, то нужно также передать выровненные тестовые данные и их метки. Немного подождав окончания тренировки, можно вывести результаты на график. Вот код для построения простого графика. Мы видим, что точность во время обучения растёт как надо, а вот точность на валидационных данных хотя и неплоха, но далека от совершенства. Но что любопытно — так это график функции потерь справа. Функция потерь на тренировочных данных идёт вниз, а на валидационных — растёт. Почему бы это?

11(w2)-video9: Let’s talk about the loss (17.MLg_3c)

Think about loss in this context, as a confidence in the prediction. So while the number of accurate predictions increased over time, what was interesting was that the confidence per prediction effectively decreased. You may find this happening a lot with text data. So it's very important to keep an eye on it. One way to do this is to explore the differences as you tweak the hyperparameters. So for example, if you consider these changes, a decrease in vocabulary size, and taking shorter sentences, reducing the likelihood of padding, and then rerun, you may see results like this. Here, you can see that the loss has flattened out which looks good, but of course, your accuracy is not as high. Another tweak. Changing the number of dimensions using the embedding was also tried. Here, we can see that that had very little difference. Putting the hyperparameters as separate variables like this is a useful programming exercise, making it much easier for you to tweak and explore their impact on training. Keep working on them and see if you can find any combinations that give a 90 percent plus training accuracy without a cost of the lost function increasing sharply. In the next video, we'll also look at the impact of splitting our words into sub-tokens and how that might impact your training.
---------------------------------------------------------------
Функцию потерь здесь стоит рассматривать как надёжность предсказания. Если число точных предсказаний у нас увеличивалось с течением времени, то интересно при этом то, что надёжность отдельно взятых предсказаний при этом снижалась. Такое может очень часто наблюдаться для текстовых данных. Поэтому очень важно следить за надёжностью. Один из способов — изучать разницу в процессе подстройки гиперпараметров. Например, если взять такие изменения, как уменьшение размера словаря [было 10 000, стало 1000 - прим пер.] и сокращение длины предложений, [16 вместо 32 - прим.пер.] благодаря которому последовательности реже дополняются, — и снова запустить код, то результаты будут примерно такие. Видно, что функция потерь стала плоской, что хорошо. Но точность, разумеется, уже не так высока. Можно попробовать другое изменение: изменить размерность эмбеддинга. Здесь мы видим, что влияет оно очень слабо. Выносить гиперпараметры в отдельные переменные, как здесь, — практика, которой стоит придерживаться: так вам будет намного проще вносить поправки и исследовать их влияние на процесс тренировки. Ещё поупражняйтесь с этим, и посмотрите, получится ли у вас отыскать комбинацию, дающую точность более 90% на тренировочном наборе, не вызывая при этом резкого роста функции потерь. В следующем видео мы посмотрим, как разбиение слов на составные части скажется на процессе обучения.

12(w2)-Check out the code! (Lab 2): (17.MLg_3c)

Ungraded Lab: Training a binary classifier with the Sarcasm Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W2/ungraded_labs/C3_W2_Lab_2_sarcasm_classifier.ipynb

13(w2)-video10: Pre-tokenized datasets (17.MLg_3c)

Earlier this week, we looked at using TensorFlow Data Services, or TFDS to load the reviews from the IMDb dataset and perform classification on them. In that video, you loaded the raw text for the reviews, and tokenized them yourself. However, often with prepackaged datasets like these, some data scientists have done the work for you already, and the IMDb dataset is no exception. In this video, we'll take a look at a version of the IMDb dataset that has been pre-tokenized for you, but the tokenization is done on sub words. We'll use that to demonstrate how text classification can have some unique issues, namely that the sequence of words can be just as important as their existence.
---------------------------------------------------------------
Мы уже посмотрели на этой неделе, как использовать TensorFlow Data Services, или TFDS, чтобы загружать рецензии из набора данных IMDB и классифицировать их. В этом видео вы загрузите необработанный текст рецензий и токенизируете его самостоятельно. В случае подготовленных наборов данных, как эти, кто-то из специалистов по данным уже сделал за вас эту работу, и набор данных IMDB здесь не исключение. В этом видео мы рассмотрим другую версию набора данных IMDB, которую тоже токенизировали предварительно, но разбивку произвели по частям слов. Мы используем его, чтобы продемонстрировать, что в классификации текстов возможны свои особые нюансы. А именно, что последовательность слов может быть так же важна, как и их наличие.

14(w2)-TensorFlow datasets: (17.MLg_3c)

Please find here the datasets GitHub url.
https://github.com/tensorflow/datasets/tree/master/docs/catalog
For more information, please checkout the TensorFlow datasets documentation.
https://www.tensorflow.org/datasets/catalog/overview
---------------------------------------------------------------
Пожалуйста, найдите здесь URL-адрес GitHub наборов данных.
https://github.com/tensorflow/datasets/tree/master/docs/catalog
Для получения дополнительной информации ознакомьтесь с документацией по наборам данных TensorFlow.
https://www.tensorflow.org/datasets/catalog/overview

15(w2)-video11: Diving into the code (part 1) (17.MLg_3c)

So we'll start by looking at TensorFlow Datasets, you can find them at this URL. If you look at the IMDB reviews data-set, you'll see that there's a bunch of versions that you can use. These include,"plain_text" which we used in the last video,"bytes", where the text is encoded at byte level, and sub-word encoding which we'll look at in this video. You can now start using the imdb subwords dataset. We'll use the 8k version today. Getting access to your training and test data is then as easy as this. Next, if you want to access the sub words tokenizer, you can do it with this code. You can learn all about the sub-words texts encoder at this URL.
---------------------------------------------------------------
Итак, сначала заглянем в описание наборов данных из TensorFlow, он находится по этой ссылке. Если найти там набор imdb_reviews, то у него имеется несколько версий, доступных для использования. Сюда входят "plain_text" (плоский текст), который мы использовали в прошлом видео, а также "bytes", где текст закодирован побайтово, и набор, кодированный по частям слов, который мы рассмотрим в этом видео. Обратите внимание, что для кода, который я здесь покажу, нужно использовать TensorFlow 2.0, т.к. есть несколько несовместимостей с версией 1.x. Поэтому, если вы используете Colab, вам нужно сначала вывести версию TF. Если она 1.x, придётся сначала установить TensorFlow 2, как указано здесь. Обратите внимание, что с течением времени "-alpha0" нужно будет заменить на более поздние версии. Поэтому при любых трудностях советую вам обратиться к актуальному руководству по установке TensorFlow 2.0. Советую запустить эту строку ещё раз, чтобы убедиться, что теперь у вас версия 2, — прежде чем двинуться дальше. Особенно если вы используете Colab или Jupyter Notebook. Установив TensorFlow 2, можно начать использовать набор данных imdb с разбивкой слов на части. Сегодня мы используем версию 8k. Здесь показано, насколько просто получить тренировочный и тестовый наборы данных. А чтобы получить доступ к токенизатору по фрагментам слов, нужно выполнить данный код. Получить полную информацию о разбиении по частям слов можно по этой ссылке.

16(w2)-Subwords text encoder: (17.MLg_3c)

The documentation for the subword text encoder can be found here
https://www.tensorflow.org/datasets/api_docs/python/tfds/deprecated/text/SubwordTextEncoder---------------------------------------------------------------

17(w2)-video11: Diving into the code (part 2) (17.MLg_3c)

We have a pre-trained sub-words tokenizer now, so we can inspect its vocabulary by looking at its sub-words property. If we want to see how it encodes or decode strings, we can do so with this code. So we can encode simply by calling the encode method passing it the string. Similarly, decode by calling the decode method. We can see the results of the tokenization when we print out the encoded and decoded strings. If we want to see the tokens themselves, we can take each element and decode that, showing the value to token. Note that this is case sensitive and punctuation is maintained unlike the tokenizer we saw in the last video. You don't need to do anything with them yet, I just wanted to show you how sub-word tokenization works. So now, let's take a look at classifying IMDB with it. What the results are going to be? Here's the model. Again, it should look very familiar at this point. One thing to take into account though, is the shape of the vectors coming from the tokenizer through the embedding, and it's not easily flattened. So we'll use Global Average Pooling 1D instead.
Here's the output of the model summary. You can compile and train the model like this, it's pretty standard. You can graph the results with this code, and your graphs will probably look something like this. sub-word meanings are often nonsensical and it's only when we put them together in sequences that they have meaningful semantics. Thus, some way from learning from sequences would be a great way forward, and that's exactly what you're going to do next week with recurrent neural networks
---------------------------------------------------------------
Теперь у нас есть предобученный токенизатор по фрагментам слов, так что мы можем изучить его словарь, обратившись к его полю tokenizer.subwords. А посмотреть, как он кодирует или декодирует строки, можно с помощью данного кода. Для кодирования нужно просто вызвать метод encode, передав в него строку. Декодировать — аналогично, вызовом метода decode. Чтобы увидеть результат токенизации, выведем закодированную и декодированную строки. Чтобы увидеть сами токены, можно декодировать все элементы по очереди, выводя значения и их токены. Обратите внимание, что этот токенизатор чувствителен к регистру, и сохраняет знаки препинания, в отличие от того, который мы видели в предыдущем видео. Вам пока не надо ничего с ним делать, я просто хотел показать вам, как работает токенизация по частям слов. А теперь посмотрим, как работает классификация IMDB на его основе. Какими будут результаты? Вот модель. Опять же, она теперь должна выглядеть для вас знакомо. Но следует принять во внимание, что вектору, приходящему из токенизатора через эмбеддинг, не так просто придать одномерный вид. Так что мы используем GlobalAveragePooling1D вместо Flatten.
Здесь выведена сводная информация о модели. Можно скомпилировать и обучить модель, как здесь, это типовой код. Можно вывести результаты на график с помощью этого кода. И ваш график, вероятно, будет выглядеть примерно так. Части слов обычно не несут никакого смысла, и только когда мы составляем из них последовательности, они приобретают значение. А значит, некий способ обучаться на таких последовательностях стал бы большим шагом вперёд, и как раз этим мы и займёмся на следующей неделе, когда рассмотрим рекуррентные нейросети.

18(w2)-Check out the code! (Lab 3): (17.MLg_3c)

Ungraded Lab: Subword Tokenization with the IMDB Reviews Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W2/ungraded_labs/C3_W2_Lab_3_imdb_subwords.ipynb

19(w2)- Week 2 Quiz: (17.MLg_3c)

1) what is the name of the TensorFlow library containing common data that you can use to train and test neural networks?:
1. There is no library of common data sets, you have to use your own
2. TensorFlow Data
3. TesorFlow Data Libraries
4. TensorFlow Datasets (+)
2) How many reviews are there is the IMDB dataset and how are they split?:
1. 50,000 records, 80/20 train/test split
2. 60,000 records, 80/20 train/test split
3. 50,000 records, 50/50 train/test split (- +)
4. 60,000 records, 50/50 train/test split
3) How are the labels for the IMDB dataset encoded? in Python:
1. Reviews encoded as a number 0-1 (+)
2. Reviews encoded as a number 1-10
3. Reviews encoded as a boolean true/false
4. Reviews encoded as a number 1-5 (-)
4) What is the purpose of the embedding dimension?:
1. It is the number of dimensions required to encode every word in the corpus
2. It is the number of letters in the word, denoting the size of the encoding
3. it is the number of words to encode in the imbedding
4. It is the number of dimensions for the vector representing the word encoding (+)
5) When tokenizing a corpus, what does the num_words=n parameter do?:
1. It specifies the maximum number of words to be tokenized, and picks the most common 'n-1' words(+)
2. It specifies the maximum number of words to be tokenized, and picks the first 'n' words that were tokenized
3. It errors out if there are more than n distinct words iin the corpus
4. It specifies the maximum number of words to be tokenized, and stops tokenizing when it reaches n
6) To use word embeddings in TensorFlow, in a sequential layer, what is the name of the class?:
1. tf.keras.layers.Embed
2. tf.keras.layers.WordEmbedding
3. tf.keras.layers.Embedding (+)
4. tf.keras.layers.Word2Vector
7) IMDB Reviews are either positive of negative. What type of loss function should be used in this scenario?:
1. Adam
2. Binary Gradient descent
3. Categorical crossentropy
4. Binary crossentropy (+)
8) When using IMDB Sub Words Dataset, our results in classification were poor. Why?:
1. Our neural network didn't have enough layers
2. We didn't train long enough (-)
3. Sequence becomes much more important when dealing with subwords, but we're ignoring word positions (+)
4. The sub words make no sense, so can't be classified

20(w2)- Week 2 Wrap up: (17.MLg_3c)

Here are the key takeaways for this week:
- You looked at taking your tokenized words and passing them to an Embedding layer.
- Embeddings map your vocabulary to vectors in higher-dimensional space.
- The semantics of the words were learned when those words were labeled with similar meanings. For example, when looking at movie reviews, those movies with positive sentiment had the dimensionality of their words ending up pointing a particular way, and those with negative sentiment pointing in a different direction. From these, the words in future reviews could have their direction established and your model can infer the sentiment from it.
- You then looked at subword tokenization and saw that not only do the meanings of the words matter but also the sequence in which they are found.
Next week, you will:
-Look at other network architectures that you can use when building NLP models.
- Use Recurrent Neural Networks to take note of the sequence of your tokens.
- Use a convolutional layer to extract features from your model.
- Compare the performance of different architectures in building binary classifiers.
---------------------------------------------------------------
Here are the key takeaways for this week:
- You looked at taking your tokenized words and passing them to an Embedding layer.
- Embeddings map your vocabulary to vectors in higher-dimensional space.
- The semantics of the words were learned when those words were labeled with similar meanings. For example, when looking at movie reviews, those movies with positive sentiment had the dimensionality of their words ending up pointing a particular way, and those with negative sentiment pointing in a different direction. From these, the words in future reviews could have their direction established and your model can infer the sentiment from it.
- You then looked at subword tokenization and saw that not only do the meanings of the words matter but also the sequence in which they are found.
Next week, you will:
-Look at other network architectures that you can use when building NLP models.
- Use Recurrent Neural Networks to take note of the sequence of your tokens.
- Use a convolutional layer to extract features from your model.
- Compare the performance of different architectures in building binary classifiers.

21(w2)- Lecture Notes Week 2: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/natural-language-processing-tensorflow/ungradedLti/jF6xb/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License. DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
ou may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode

22(w2)- Programming Assignment: Diving deeper into the BBC News archive2: (17.MLg_3c)

C3W2_Assignment
Week 2: Diving deeper into the BBC News archive

NEXT week_3 (17.MLg_3c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3)Assessments Overdue (17.MLg_3c)

(Оценки просрочены)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video: 10 minutes
Self-study: 3h 16 min
Graded tasks (Tasks to be assessed): 2

(w3) Content (17.MLg_3c)

1. LSTM Long Short-Term Memory. LSTM (долгая краткосрочная память) является типом рекуррентной нейронной сети (RNN).
2. IMDB Subwords 8K with Single Layer LSTM
3. IMDB Subwords 8K with Multi Layer LSTM
4. GRU — Gated Recurrent Unit
5. Using Convolutional Neural Networks
6. IMDB Reviews with LSTM, GRU and Conv1D
7. Sarcasm with Bidirectional LSTM
8. Sarcasm with 1D Convolutional Layer

(w3) Introduction: (17.MLg_3c)

In the last couple of weeks you looked first at Tokenizing words to get numeric values from them, and then using Embeddings to group words of similar meaning depending on how they were labelled. This gave you a good, but rough, sentiment analysis -- words such as 'fun' and 'entertaining' might show up in a positive movie review, and 'boring' and 'dull' might show up in a negative one. But sentiment can also be determined by the sequence in which words appear. For example, you could have 'not fun', which of course is the opposite of 'fun'. This week you'll start digging into a variety of model formats that are used in training models to understand context in sequence!
---------------------------------------------------------------
За последние пару недель вы сначала посмотрели на токенизацию слов, чтобы получить из них числовые значения, а затем использовали вложения для группировки слов схожего значения в зависимости от того, как они были помечены. Это давало вам хороший, но грубый анализ настроений — такие слова, как «весело» и «развлекательный», могли появиться в положительном обзоре фильма, а «скучный» и «скучный» — в отрицательном. Но настроение также можно определить по последовательности, в которой появляются слова. Например, у вас может быть «не весело», что, конечно, противоположно «весело». На этой неделе вы начнете изучать различные форматы моделей, которые используются в обучающих моделях для последовательного понимания контекста!

1(w3)-video1: A conversation with Andrew Ng (17.MLg_3c)

Welcome back. In this video, you'll learn how to implement sequence models, in TensorFlow, and if you've heard of models like an RNN, or Recurrent Neural Network, this week we'll teach you how to implement that. It's important to really take words, and compute embeddings for them, but the relative ordering, the sequence of words matters too for the meaning of a sentence, and if you jumble the words around, that changes, or destroys the meaning of a sentence. Definitely, and so if you take just a very simple sentence, like my dog sat on my hat, and you swap the words dog, and hat, you're now changing from a sentence that has some kind of meaning, and some semantics, to a ridiculous sentence that has no meaning, right? My hat sat on my dog, unless you have a really smart hat, it doesn't really mean anything. So when we were doing classification based on embeddings, it was very nice that we had words with similar meanings, labels in a particular way, so that we could say okay, this is a positive review, and I got a bunch of vectors that are similar, this is a negative review, and I got these vectors in a similar way, but ordering those then gives us that whole extra layer of meaning that'll help us to understand the sentence rather than just a simple classification. So for a neural network, to take into account the ordering of the words, people now use specialized Neural Network Architectures, things like an RNN, or GIO, or LSTM, and you see what all these terms mean, and a little bit, in order for these Specialized Neural Networks to process natural language. Yeah. So like something like an RNN, it's really interesting that, the context is preserved from timestamp to timestamp, which can be really useful, but that might get lost in longer sentences, and that's why I really love LSTMs because LSTMs have that cell state, and the cell state are almost like a conveyor belts carrying contexts all the way down, for a long way down timestamp. I love that you have a favorite flavor on how sequence follow. I hold no shame, and keeping favorites. So then, in a really long sentence, like for example, I grew up in Ireland, so I went to school, and at school, they made me learn how to speak something. It's like you could say, okay the context from speak, means that it's a language, but you have to go all the way back to the beginning of the sentence to see that it's Ireland, and then in Ireland, I would learn how to speak. You speak Gaelic. Really badly. Since we learn to invent all of these things. Let's go on to the next video.
---------------------------------------------------------------
И снова здравствуйте. Из этого видео вы узнаете, как реализовать модели последовательностей в TensorFlow. И если вы слышали о таких моделях, как РНС, т.е., Рекуррентные Нейронные Сети, то на этой неделе мы научим вас, как их реализовывать. Важно брать сами слова и вычислять для них эмбеддинги, но и относительный порядок, последовательность слов — также имеет значение для смысла предложения. Если перемешать все слова, это изменит или уничтожит смысл предложения. Да, определённо, взять хоть простое предложение, скажем, "My dog sat on my hat" (Моя собака сидела на моей шляпе). Поменяйте местами слова dog и hat, и вы из предложения, у которого был какой-то смысл и определённое значение, получите абсурдное и бессмысленное предложение, верно? My hat sat on my dog (Моя шляпа сидела на моей собаке) Если только у вас нет действительно учёной шляпы, это на самом деле ничего не значит. Это как при классификации на основе эмбеддингов нам помогало то, что близкие по смыслу слова размечались таким образом, что можно было сказать: "Вот это — положительная рецензия", и получить набор похожих векторов, "А это — отрицательная рецензия" — и тоже получить подобные вектора. Но если выстроить слова по порядку, то это даст нам целый дополнительный слой значений, и поможет понять само предложение, не ограничиваясь простой классификацией. Итак, чтобы нейросеть могла принимать во внимание порядок слов, сейчас используют особую архитектуру нейросетей, такую, как РНС, или GIO, или LSTM, (вы скоро узнаете, что означают все эти термины) — чтобы специализированные нейросети могли обрабатывать естественный язык. Да, нечто вроде РНС, и здесь по-настоящему интересно, что контекст (вычислений) сохраняется от одной отметки времени до следующей, что может быть очень полезно, — но при длинных предложениях этот контекст [в РНС] может исчезать, и вот почему мне так нравятся LSTM: потому что в LSTM есть вектор состояний, и этот вектор состояний похож на ленту конвейера, которая всё время тащит этот контекст, сохраняя его долгое время. Мне нравится, что у вас есть любимый подход к работе с последовательностями. Мне не стыдно, что у меня есть любимчики. Итак, в действительно длинном предложении, например, "Я вырос в Ирландии, и там я ходил в школу, и в школе меня заставляли учиться говорить &lt;на чём-то&gt;." И тут можно было бы сказать: по контексту, "говорить" означает, что речь идёт о языке, но тут нужно вернуться далеко назад, к началу предложения, и увидеть, что это Ирландия, а на чём я должен был учиться говорить в Ирландии? Вы говорите на гэльском. Да! Но очень плохо. И чтобы обучать всему этому с нуля, давайте перейдём к следующему видео.

2(w3)-video2: Introduction (17.MLg_3c)

Last week, we looked at doing classification using texts and trying to train and understand positive and negative sentiment in movie reviews. We finished by looking at the effect of tokenizing words, and saw that our classifier failed to get any meaningful results. The main reason for this was that the context of words was hard to follow when the words were broken down into sub-words and the sequence in which the tokens for the sub-words appear becomes very important in understanding their meaning. Let's take a look at that now. The neural network is like a function that when you feed it in data and labels, it infers the rules from these, and then you can use those rules. So it could be seen as a function a little bit like this, you take the data and you take the labels, and you get the rules. But this doesn't take any kind of sequence into account. To understand why sequences can be important, consider this set of numbers. If you've never seen them before, they're called the Fibonacci sequence. So let's replace the actual values with variables such as n_0, n_1 and n_2, etc., to denote them. Then the sequence itself can be derived where a number is the sum of the two numbers before it. So 3 is 2 plus 1, 5 is 2 plus 3, 8 is 3 plus 5, etc. Our n_x equals n_x minus 1, plus n_x minus 2, where x is the position in the sequence. Visualized, it might also look like this, one and two feed into the first function and three comes out. Two gets carried over to the next, where it's fed in along with the three to give us a five. The three is carried on to the next where it's fed into the function along with the five to get an eight and so on. This is similar to the basic idea of a recurrent neural network or RNN, which is often drawn a little like this. You have your x as in input and your y as an output. But there's also an element that's fed into the function from a previous function. That becomes a little more clear when you chain them together like this, x_0 is fed into the function returning y_0. An output from the function is then fed into the next function, which gets fed into the function along with x_2 to get y_2, producing an output and continuing the sequence. As you can see, there's an element of x_0 fed all the way through the network, similar with x_1 and x_2 etc. This forms the basis of the recurrent neural network or RNN. I'm not going to go into detail and how they work, but you can learn much more about them at this course from Andrew.
---------------------------------------------------------------
На прошлой неделе мы посмотрели, как классифицировать тексты, и попробовали обучать и различать положительные и отрицательные эмоции в кинорецензиях. Мы остановились на том, как влияет разбиение слов на части, и увидели, что у нашего классификатора не выходит получить хоть сколько-нибудь значимые результаты. Главная причина была в том, что контекст слов трудно уловить, если разбивать их на составные части, и конкретная последовательность, в которой идут эти части, играет очень важную роль в понимании значения. Давайте посмотрим. Нейросеть похожа на функцию, в которую вы подаёте данные и метки, а она извлекает из них правила, и затем можно эти правила использовать. Так что её можно рассматривать как функцию примерно такого вида: вы берёте данные и метки, и получаете правила. Но здесь не учитываются никакие последовательности. Чтобы понять, почему может быть важна именно последовательность, рассмотрим этот набор чисел. Если вы никогда его раньше не видели, то он называется последовательностью Фибоначчи. Заменим его значения, на обозначающие их переменные n_0, n_1, n_2, и так далее. Тогда можно вывести, что последовательность состоит в том, что очередное число является суммой двух предыдущих. Так, 3 = 2 + 1, 5 = 2 + 3 8 = 3 + 5, и т. д. n_x = n_x-1 + n_x-2, n_x = n_x-1 + n_x-2, где x — позиция числа в последовательности. Можно также изобразить это в таком виде. 1 и 2 попадают на вход первой функции, и из неё выходит 3, 2 переходит на следующий слой, где попадает на вход вместе с 3, и даёт 5. 3 переходит на следующий слой, попадая на вход функции вместе с 5, чтобы получилось 8, и так далее. Всё это очень близко к сути рекуррентной нейросети, РНС, которую часто изображают в таком духе. У вас есть вход x и выход y. Но есть ещё элемент, который попадает на вход функции из предыдущей функции. Будет немного понятнее, если развернуть сеть таким образом: x_0 попадает на вход функции, которая возвращает y_0. Выход из этой функции попадает на вход следующей функции, результат которой попадает на вход вместе с x_2, чтобы получить y_2, снова давая выходное значение, и тем самым продолжая последовательность. Как видите, здесь результат от x_0 проходит через всю сеть, и то же самое для x_1, x_2, и так далее. Это и является основой рекуррентной нейросети, или РНС. Я не собираюсь вдаваться подробно в то, как они работают, но вы можете больше узнать об этом вот в этом курсе Эндрю.

3(w3)-Link to Andrew's sequence modeling course: (17.MLg_3c)

Here is the link to Andrew's course on sequence modeling.
https://www.coursera.org/lecture/nlp-sequence-models/deep-rnns-ehs0S
---------------------------------------------------------------

4(w3)-video3: LSTMs (17.MLg_3c)

There can be a limitation when approaching text classification in this way. Consider the following. Here's a sentence. Today has a beautiful blue. What do you think would come next? Probably sky. Right? Today has a beautiful blue sky. Why would you say that? Well, there's a big clue in the word blue. In a context like this, it's quite likely that when we're talking about a beautiful blue something, we mean a beautiful blue sky. So, the context word that helps us understand the next word is very close to the word that we're interested in. But, what about a sentence like this, I lived in Ireland so at school they made me learn how to speak something. How would you finish that sentence? Well, you might say Irish but you'd be much more accurate if you said, I lived in Ireland so at school they made me learn how to speak Gaelic. First of course, is the syntactic issue. Irish describes the people, Gaelic describes the language. But more importantly in the ML context is the key word that gives us the details about the language. That's the word Ireland, which appears much earlier in the sentence. So, if we're looking at a sequence of words we might lose that context. With that in mind an update to RNNs is called LSTM, long short - term memory has been created. In addition to the context being passed as it is in RNNs, LSTMs have an additional pipeline of contexts called cell state. This can pass through the network to impact it. This helps keep context from earlier tokens relevance in later ones so issues like the one that we just discussed can be avoided. Cell states can also be bidirectional. So later contexts can impact earlier ones as we'll see when we look at the code. The detail about LSTMs is beyond the scope of this course but you can learn more about them in this video from Andrew.
---------------------------------------------------------------
Когда мы строим классификацию текстов таким образом, то можем столкнуться с ограничением. Подумайте вот о чём. Пусть есть предложение: "Сегодня красивое голубое &lt;...&gt;." Что, по-вашему, идёт дальше? Возможно, небо. Верно? Сегодня красивое голубое небо. Почему вы так сказали? Ну, существенной подсказкой служит слово "голубое". В подобных контекстах весьма вероятно, что при упоминании чего-то красивого и голубого мы имеем в виду красивое голубое небо. Контекстуальное слово, которое помогает нам понять, каким должно быть следующее слово, здесь стоит рядом с нужным нам словом. Но что вы скажете о таком предложении: "Я жил в Ирландии, так что в школе меня заставляли учиться говорить &lt;...&gt;" Как можно завершить предложение? Можно было бы сказать "по-ирландски", но будет намного точнее сказать: "Я жил в Ирландии, так что в школе меня заставляли учиться говорить по-гэльски." Конечно, прежде всего, это вопрос синтаксиса. "Ирландский" описывает человека, а "гэльский" описывает язык. Но для машинного обучения важнее то, какое ключевое слово даёт нам ответ, каким должен быть язык. Это слово — "Ирландия", которое встречается в предложении намного раньше. И если смотреть на последовательность слов, то можно потерять этот контекст. С учётом этого и был создан улучшенный вариант РНС — сети LSTM, или "Долгая краткосрочная память" (Long Short-term Memory). В дополнение к контексту, который как и в РНС, передаётся в сеть, у LSTM есть дополнительный "конвейер" контекста называемый вектором состояний. Он передаётся по сети, влияя на её работу. Это помогает хранить контекст от более ранних токенов, значимый для более поздних, чтобы избежать проблем, которые мы только что обсудили. Вектор состояний также может быть двунаправленным. То есть, более поздний контекст может влиять на более ранний, как мы убедимся при изучении кода. Подробности устройства LSTM выходят за рамки этого курса, но вы можете больше узнать о них из этого видео Эндрю.

5(w3)-More info on LSTMs: (17.MLg_3c)

Please find here a link to more information on LSTMs (Long Short Term Memory cells) by Andrew.
https://www.coursera.org/lecture/nlp-sequence-models/long-short-term-memory-lstm-KXoay
---------------------------------------------------------------

6(w3)-video4: Implementing LSTMs in code (17.MLg_3c)

So let's now take a look at how to implement LSTMs in code. Here's my model where I've added the second layer as an LSTM. I use the tf.keras.layers.LSTM to do so. The parameter passed in is the number of outputs that I desire from that layer, in this case it's 64. If I wrap that with tf.keras.layers.Bidirectional, it will make my cell state go in both directions. You'll see this when you explore the model summary, which looks like this. We have our embedding and our bidirectional containing the LSTM, followed by the two dense layers. If you notice the output from the bidirectional is now a 128, even though we told our LSTM that we wanted 64, the bidirectional doubles this up to a 128. You can also stack LSTMs like any other keras layer by using code like this. But when you feed an LSTM into another one, you do have to put the return sequences equal true parameter into the first one. This ensures that the outputs of the LSTM match the desired inputs of the next one. The summary of the model will look like this. Let's look at the impact of using an LSTM on the model that we looked at in the last module, where we had subword tokens.
---------------------------------------------------------------
Теперь посмотрим, как реализовать LSTM в коде. Вот моя модель, в которую я добавил вторым слоем LSTM. Для этого я использую keras.layers.LSTM. Туда передаётся параметр, который обозначает нужное число выходов из слоя, здесь это 64. Если обернуть этот слой в tf.keras.layers.Bidirectional, это заставляет мой вектор состояний передаваться в обе стороны. Это будет отражено в сводке о модели, которая выглядит вот так. У нас есть слой эмбеддинга и двунаправленный слой LSTM, за которым следуют два полносвязных слоя. Если вы заметили, выход из двунаправленного слоя сейчас имеет размерность 128, хотя мы и указали, что на выходе из LSTM хотим размерность 64. Двунаправленность удваивает его до 128. Слои LSTM можно выстраивать друг за другом, как и любые другие слои в keras, с помощью подобного кода. Но когда вы направляете выход одного LSTM слоя в другой, нужно передать параметр return_sequences=True в первый из них. Тем самым обеспечивается соответствие размерности выхода из LSTM-слоя входному размеру следующего слоя. Сводка о модели будет выглядеть примерно так. Давайте посмотрим, как использование LSTM скажется на модели, которую мы разбирали в прошлом модуле, когда разбивали слова на части.

7(w3)-Check out the code! (Lab 1 & Lab 2): (17.MLg_3c)

We've created a number of notebooks for you to explore the different types of sequence models.
Spend some time going through these to see how they work, and what the impact of different layer types have on training for classification.
IMDB Subwords 8K with Single Layer LSTM
Ungraded Lab: Single Layer LSTM
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_1_single_layer_LSTM.ipynb
IMDB Subwords 8K with Multi Layer LSTM
Ungraded Lab: Multiple LSTMs
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_2_multiple_layer_LSTM.ipynb
---------------------------------------------------------------

8(w3)-video5: Accuracy and loss (17.MLg_3c)

Here's the comparison of accuracies between the one layer LSTM and the two layer one over 10 epochs. There's not much of a difference except the nosedive and the validation accuracy. But notice how the training curve is smoother. I found from training networks that jaggedness can be an indication that your model needs improvement, and the single LSTM that you can see here is not the smoothest. If you look at loss, over the first 10 epochs, we can see similar results. But look what happens when we increase to 50 epochs training. Our one layer LSTM, while climbing in accuracy, is also prone to some pretty sharp dips. The final result might be good, but those dips makes me suspicious about the overall accuracy of the model. Our two layer one looks much smoother, and as such makes me much more confident in its results. Note also the validation accuracy. Considering it levels out at about 80 percent, it's not bad given that the training set and the test set were both 25,000 reviews. But we're using 8,000 sub-words taken only from the training set. So there would be many tokens in the test sets that would be out of vocabulary. Yet despite that, we are still at about 80 percent accuracy. Our loss results are similar with the two layer having a much smoother curve. The loss is increasing epoch by epoch. So that's worth monitoring to see if it flattens out in later epochs as would be desired. I hope this was a good introduction into how RNNs and LSTMs can help you with text classification. Their inherent sequencing is great for predicting unseen text if you want to generate some, and we'll see that next week. But first, I'd like to explore some other RNN types, and you'll see those in the next video.
---------------------------------------------------------------
Вот сравнение точностей между однослойной и двухслойной LSTM в течение 10 эпох. Разница не такая большая, за исключением того, что валидационная точность (первой) пикирует в конце. Но обратите внимание, что кривая обучения более гладкая. Обучая нейросети, я узнал, что её зазубренность может быть признаком того, что модель нуждается в улучшениях. И у однослойной LSTM, как видите, кривая не самая гладкая. Если взглянуть на график функции потерь в течение первых 10 эпох, вы увидите похожие результаты. Но посмотрите, что происходит, когда мы продляем обучение до 50 эпох. Наша однослойная LSTM, хотя её точность и растёт, подвержена при этом резким провалам. Конечный результат, может, и хорош, но эти провалы порождают у меня подозрения о точности модели в целом. Кривая двухслойной модели выглядит намного более гладкой, и внушает мне куда больше уверенности в результате. Обратите внимание также на валидационную точность и на то, что она выравнивается на уровне порядка 80%. Не так уж плохо, если учесть, что и тренировочный набор, и тестовый — состояли из 25 000 рецензий, но мы использовали 8000 различных частей слов, взятых только из тренировочного набора. Так что в тестовом наборе может быть много токенов, не попавших в словарь. И несмотря на это, мы всё равно достигли точности порядка 80%. Графики функции потерь похожи, и двухслойная сеть опять имеет намного более гладкую кривую. Величина потерь растёт эпоха за эпохой. За этим стоит следить, чтобы увидеть, не выравнивается ли график в более поздних эпохах, что было бы желательно. Надеюсь, это послужило хорошим введением в то, как РНС и LSTM помогают классифицировать тексты. Присущая им способность работать с последовательностями очень хороша для предсказывания ещё не виденного текста, когда нужно сгенерировать новый текст, в чём мы убедимся на следующей неделе. А пока я бы хотел разобрать некоторые другие разновидности РНС, и вы увидите их в следующем видео.

9(w3)-video6: A word from Laurence (17.MLg_3c)

In the last video we saw LSTMs and how they work with cell state to help keep context in a way that helps with understanding language. Well, words that aren't immediate neighbors can affect each other's context.
In this video, you'll see some other options of RNN including convolutions, Gated Recurrent Units also called GRUs, and more on how you can write the code for them. You'll investigate the impact that they have on training. I'm not going to go into depth on how they work, and that information is available in the deep learning specialization from Andrew. So do check it out there.
---------------------------------------------------------------
В прошлом видео мы посмотрели на LSTM и на то, как они работают с вектором состояния, чтобы сохранять контекст так, чтобы это помогало нам понимать язык. Слова, которые не стоят непосредственно рядом, могут влиять на контекст друг друга.
В этом видео вы увидите некоторые другие возможности РНС, включая свёртки, управляемые рекуррентные блоки (УРБ) [GRU — Gated Recurrent Unit - прим. пер.] и другие. А также как использовать их в своём коде. Вы изучите, как они влияют на обучение. Я не собираюсь подробно излагать механизм их работы, эта информация доступна в специализации Эндрю "Глубокое обучение". Так что можете посмотреть там.

10(w3)-video7: Looking into the code (17.MLg_3c)

So let's start with this basic neural network. It has an embedding taking my vocab size, embedding dimensions, and input length as usual. The output from the embedding is averaged and then fed into a dense neural network. But we can experiment with the layers that bridge the embedding and the dense by removing the pooling from here, and replacing them with an LSTM like this. If I train using the sarcasm data-set with these, when just using the pooling I quickly got close to 85 percent accuracy and then it flattened out there. The validation set was a little less accurate, but the curves we're quite in sync.
On the other hand, when using LSTM, I reached 85 percent accuracy really quickly and continued climbing towards about 97.5 percent accuracy within 50 epochs. The validation set dropped slowly, but it was still close to the same value as the non- LSTM version. Still the drop indicates that there's some over fitting going on here. So a bit of tweaking to the LSTM should help fix that. Similarly, the loss values from my non-LSTM one got to healthy state quite quickly and then flattened out. Whereas with the LSTM, the training loss drop nicely, but the validation one increased as I continue training. Again, this shows some over fitting in the LSTM network. While the accuracy of the prediction increased, the confidence in it decreased. So you should be careful to adjust your training parameters when you use different network types, it's not just a straight drop-in like I did here.
---------------------------------------------------------------
Итак, начнём с этой базовой нейросети. В ней есть слой эмбеддинга с параметрами, описывающими размер словаря, размерность эмбеддингов и длина входной последовательности, как обычно. Выход из эмбеддинга разворачивается в одномерный массив, усредняется и поступает на вход полносвязной нейросети. Здесь можно поэкспериментировать со слоями, которые связывают эмбеддинг и плотный слой, удалив отсюда разворачивание и усреднение и заменив их на LSTM, как здесь. Обучая на данных, посвящённых сарказму, и используя только усреднение и разворачивание эмбеддингов, я быстро подошёл к 85% точности, но потом она вышла на плато. Точность на валидационном наборе была несколько меньше, но кривые шли довольно согласованно. С другой стороны, при использовании LSTM я очень быстро достиг 85% точности, и продолжал наращивать её вплоть до 97.5% после 50 эпох. Точность на валидационном наборе медленно падала, но оставалась достаточно близкой к показателям версии без LSTM. Тем не менее, это падение указывает на то, что тут имеет место переобучение. Так что небольшая подстройка параметров LSTM должна это исправить. Аналогичным образом, значение функции потерь моей версии без LSTM довольно быстро достигло хороших показателей, а затем перестало снижаться. В то время как LSTM успешно снижала потери на тренировочном наборе, но на валидационном они росли по мере продолжения обучения. Повторю, что это признак того, что LSTM-сеть переобучается. И хотя точность предсказания увеличилась, уверенность в нём уменьшилась. Так что нужно внимательно подбирать параметры обучения при использовании сетей разных типов. Нельзя просто так взять, и совместить их, как я поступил здесь.

11(w3)-video8: Using a convolutional network (17.MLg_3c)

Another type of layer that you can use is a convolution, in a very similar way to what you did with images. The code to use a convolutional on network is here. It's very similar to what you had before. You specify the number of convolutions that you want to learn, their size, and their activation function. The effect of this will then be the same. Now words will be grouped into the size of the filter in this case 5. And convolutions will learned that can map the word classification to the desired output. If we train with the convolutions now, we will see that our accuracy does even better than before with close to about 100% on training and around 80% on validation. But as before, our loss increases in the validation set, indicating potential overfilling. As I have a super simple network here, it's not surprising, and it will take some experimentation with different combinations of convolutional layers to improve on this. If we go back to the model and explore the parameters, we'll see that we have 128 filters each for 5 words. And an exploration of the model will show these dimensions. As the size of the input was 120 words, and a filter that is 5 words long will shave off 2 words from the front and back, leaving us with 116. The 128 filters that we specified will show up here as part of the convolutional layer.
---------------------------------------------------------------
Ещё один тип слоёв, который здесь можно использовать — это свёрточный, его применение похоже на то, как было с изображениями. На экране код использования этого слоя в нейросети. Всё очень похоже на то, что было раньше: задаёте количество свёрток, которые вы хотите обучать, их размер и функцию активации. Результат тоже будет прежним. Теперь слова будут сводиться в группы, их равен размеру фильтра — здесь это 5. И свёртки будут учиться превращать классифицируемые слова в желаемые выходные значения. Если теперь обучить свёртку, то мы увидим, что точность стала даже лучше, чем раньше, она близка к 100% на тренировочном наборе и около 80% на валидационном. Но, как и раньше, на валидационном наборе наша функция потерь растёт, сигнализируя о потенциальном переобучении. И т.к. у меня крайне простая сеть, то в этом нет ничего удивительного, и потребуется ряд экспериментов с различными комбинациями свёрточных слоёв, чтобы добиться здесь улучшения. Если мы вернёмся к модели и исследуем параметры, то увидим, что у нас есть 128 фильтров, каждый на 5 слов. А если заглянуть в модель, то размерности будут следующими. Поскольку размер входа 120 слов, а фильтру нужно 5 слов, он отрежет по 2 слова в начале и в конце, оставив нам 116. 128 фильтров, которые мы указали, можно увидеть здесь, в составе свёрточного слоя.

12(w3)-Check out the code! (Lab 3): (17.MLg_3c)

Spend some time going through this notebook to see how it works.
IMDB Subwords 8K with 1D Convolutional Layer
Ungraded Lab: Using Convolutional Neural Networks
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_3_Conv1D.ipynb

13(w3)-video9: Going back to the IMDB dataset (17.MLg_3c)

So now that we've seen these, let's go back to the IMDB dataset that we used earlier in this course. Here, I'll just use an embedding that I flattened before it goes into the dense. My model will look like this, with a 171,533 parameters, and the performance will be like this. It's nice accuracy, but clear overfitting but it only takes about five seconds per epoch to train. If I change this to use an LSTM, it will take about 43 seconds per epoch. The accuracy is better, but there's still some overfitting.
If I try a GRU layer instead, with a GRU being a different type of RNN, and I make it bidirectional, my network will have a 169,997 parameters. My training time will fall to 20 seconds per epoch, and my accuracy is again very good on training, and not too bad on validation but again, showing some overfitting. With a convolutional network, I'll have a 171,149 parameters and it only takes about six seconds per epoch to get me close to 100 percent accuracy on training, and about 83 percent on validation, but again with overfitting.
---------------------------------------------------------------
Посмотрев на свёртки, давайте вернёмся к набору данных IMDB, который мы уже использовали в этом курсе. Здесь я использую просто эмбеддинг, который я развернул в одномерный массив перед передачей в полносвязный слой. Моя модель будет выглядеть так, с 171 533 параметрами. И показатели работы будет такими. Точность тут хорошая, но переобучение очевидно. Зато обучение одной эпохи занимает всего 5 секунд. Если я изменю сеть на LSTM, в ней будет только 30 129 параметров, но на одну эпоху обучения уйдёт примерно 43 секунды. Точность лучше, но сеть всё ещё переобучается. Если я попробую взамен LSTM слой УРБ, где УРБ — ещё одна разновидность РНС, и сделаю этот слой двунаправленным, в моей сети будет 169 997 параметров. Время обучения сократится до 20 секунд на эпоху, и точность снова будет очень хорошей на тренировочном наборе и неплохой на валидационном, но снова будет некоторое переобучение. Со свёрточной сетью в сети будет 171 149 параметров, а обучение займёт лишь 6 секунд на эпоху, и точность приблизится к 100% на тренировочном наборе и около 83 процентов на валидационном. Но переобучение будет и здесь.

14(w3)-Check out the code! (Lab 4): (17.MLg_3c)

Spend some time going through this notebook to see how it works and what the impact of different layer types have on training for classification.
IMDB Reviews with LSTM, GRU and Conv1D
Ungraded Lab: Building Models for the IMDB Reviews Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_4_imdb_reviews_with_GRU_LSTM_Conv1D.ipynb
---------------------------------------------------------------

15(w3)-video10: Tips from Laurence (17.MLg_3c)

Before you go onto the next unit, I have created some CO-LABS with each of these options. Try them out for yourself, check on the time, check on the results, and see what techniques you can figure out to avoid some of the overfitting. Remember that with text, you'll probably get a bit more overfitting than you would have done with images. Not least because you'll almost always have out of vocabulary words in the validation data set. That is words in the validation dataset that weren't present in the training, naturally leading to overfitting. These words can't be classified and, of course, you're going to have these overfitting issues, but see what you can do to avoid them.
---------------------------------------------------------------
Прежде чем вы перейдёте к следующему модулю, хочу сказать, что сделал несколько блокнотов в Colab, для каждого из вариантов. Попробуйте их самостоятельно, проверьте время обучения и результаты, попробуйте выяснить, какие приёмы помогут вам избежать переобучения. Помните, что в случае текста переобучение у вас будет проявляться сильнее, чем при работе с изображениями. Не в последнюю очередь, из-за того, что у вас почти всегда в валидационном наборе будут слова не из словаря. Это слова валидационного набора, которых не было в тренировочном, что, естественно, ведёт к переобучению. Эти слова нельзя классифицировать, и, конечно, у вас будут возникать проблемы с переобучением, но попробуйте с ними справиться.

16(w3)-Exploring different sequence models (Lab 5 & Lab 6): (17.MLg_3c)

We've created a couple of notebooks for you to explore the different types of sequence models for Sarcasm Detection.
Spend some time going through these to see how they work, and what the impact of different layer types have on training for classification.
Sarcasm with Bidirectional LSTM
Ungraded Lab: Training a Sarcasm Detection Model using Bidirectional LSTMs
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_5_sarcasm_with_bi_LSTM.ipynb
Sarcasm with 1D Convolutional Layer
Ungraded Lab: Training a Sarcasm Detection Model using a Convolution Layer
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_6_sarcasm_with_1D_convolutional.ipynb
---------------------------------------------------------------

17(w3)- Week 3 Quiz: (17.MLg_3c)

1) Why does sequence make a large difference when determining semantics of language?:
1. It doesn't
2. Because the order in which words appear dictate their impact on the meaning of the sentence (+)
3. Because the order in which words appear dictate their meaning
4. Because the order of words doesn't matter
2) How do Recurrent Neural Networks help you understand the impact of sequence on meaning?:
1. They don't
2. They shuffle the words evenly
3. They carry meaning from one cell to the next (+)
4. They look at the whole sentence at a time
3)How does an LSTM help understand meaning when words that qualify each other aren't necessarily beside each other in a sentence?:
1. They shuffle the words randomly
2. They load all words into a cell state
3. They don't
4. Values from earlier words can be carried to late ones via a cell state (+)
4) What keras layer type allows LSTMs to look forward and backward in a sentence?:
1. Unilateral
2. Bothdirection
3. Bilateral
4. Bidirectional (+)
5) What's the output shape of a bidirectional LSTM laery with 64 units?:
1. (128,1)
2. (None, 128) (- +)
3. (128, None)
4. (None, 64)
6) When stacking LSTMs, how do you instruct an LSTM to feed the next one in the sequence?:
1. Ensure that return_sequences is set to True on all units
2. Ensure that return_sequences is set to True only on units that feed to another LSTM (+)
3. Do nothing, TensorFlow handles this automatically
4. Ensure that they have the same number of units
7) If a sentence has 120 tokens in it, and a Conv1D with 128 filters with a Kernal size of 5 is passed over it, what's the output shape?:
1. (None, 120, 124)
2. (None, 120, 128)
3. (None, 116, 124)
4. (None, 116, 128) (+)
8) What's the best way to avoid overfitting in NLP datasets?:
1. Use LSTMs
2. Use GRUs
3. Use Conv1D
4. None of the above (+)

18(w3)- Week 3 Wrap up: (17.MLg_3c)

You’ve been experimenting with NLP for text classification over the last few weeks. Next week, you’ll switch gears and take a look at using the tools that you’ve learned to predict text, which ultimately means you can create text. By learning sequences of words, you can predict the most common word that comes next in the sequence. Thus when starting from a new sequence of words, you can create a model that builds on them. You’ll take different training sets -- like traditional Irish songs, or Shakespeare poetry, and learn how to create new sets of words using their embeddings!
---------------------------------------------------------------
Последние несколько недель вы экспериментировали с НЛП для классификации текстов. На следующей неделе вы переключитесь и взглянете на использование инструментов, которые вы изучили, для прогнозирования текста, что в конечном итоге означает, что вы можете создавать текст. Изучая последовательности слов, вы можете предсказать наиболее распространенное слово, которое будет следующим в последовательности. Таким образом, начиная с новой последовательности слов, вы можете создать модель, основанную на них. Вы возьмете различные обучающие наборы — например, традиционные ирландские песни или поэзию Шекспира, — и научитесь создавать новые наборы слов, используя их встраивания!

19(w3)- Lecture Notes Week 3: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

20(w3)- Programming Assignment: Exploring overfitting in NLP: (17.MLg_3c)

You have not submitted. You must earn 80/100 points to pass.
Deadline
The assignment was due on Jun 19, 9:59 AM EEST
You can still pass this assignment before the course ends.
C3W3_Assignment
Week 3: Exploring Overfitting in NLP

NEXT week_4 (17.MLg_3c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w4)Sequence models and literature (17.MLg_3c)

(Модели последовательности и литература)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video:24 minutes
Self-study: 1h 26 min
Graded tasks (Tasks to be assessed): 2

(w4) Content (17.MLg_3c)

1. 2. 3.4.5.6.7.8.

(w4) Introduction: (17.MLg_3c)

Taking everything that you've learned in training a neural network based on NLP, we thought it might be a bit of fun to turn the tables away from classification and use your knowledge for prediction. Given a body of words, you could conceivably predict the word most likely to follow a given word or phrase, and once you've done that, to do it again, and again. With that in mind, this week you'll build a poetry generator. It's trained with the lyrics from traditional Irish songs, and can be used to produce beautiful-sounding verse of it's own!
---------------------------------------------------------------
Принимая во внимание все, что вы узнали при обучении нейронной сети на основе НЛП, мы подумали, что может быть немного забавно отвернуть таблицы от классификации и использовать свои знания для прогнозирования. Имея совокупность слов, вы могли бы предсказать слово, которое с наибольшей вероятностью будет следовать за данным словом или фразой, и, сделав это, повторять это снова и снова. Имея это в виду, на этой неделе вы создадите генератор стихов. Он обучен текстам традиционных ирландских песен и может быть использован для создания собственных красиво звучащих стихов!

1(w4)-video1: A conversation with Andrew Ng (17.MLg_3c)

Welcome back. One of the most fun applications of sequence models, is that they can read the body of text, so train on the certain body of text, and then generate or synthesize new texts, that sounds like it was written by similar author or set of authors. It's like, so one of the things that we're going to do in this week. In the courses, we're going to take a body of work from Shakespeare, and Shakespeare as a medieval English author, and so he wrote in a different style of English than we're used to reading, and it makes for a really interesting exercise in text generation, because if you're not familiar with like Shakespearean language and how it is done, then the language is actually generated by the neural network, will probably look a lot like the original one, probably, if you lived in the 1600's when Shakespeare was around, you'd be able to identify as being generated by a neural network, but for us now with this slightly different version of England, it actually makes for a really fun scenario. There's a really fun application in neural network, and one of my favorite teachers in high school, was actually my English teacher that made me memorize a lot of Shakespeare. I really wonder what she would think of this. Yes, I had exactly the same. I played Henry the fourth in high school. So I even, I know you all and well awhile uphold this unyoked humor of your idleness Hey, I even remember. I can't top that. So to do all this fun stuff yourself, let's go into this week's videos.
---------------------------------------------------------------
Добро пожаловать. Одно из наиболее занимательных применений последовательных моделей — это то, что они могут прочитать корпус текстов, обучиться на этих конкретных текстах? и потом генерировать, или синтезировать, новые тексты, которые будут выглядеть так, словно их написал тот же автор, или несколько авторов. И это одна из тех возможностей, которыми мы будем заниматься на этой неделе. В курсе мы возьмём собрание текстов Шекспира. А Шекспир — средневековый английский автор, и он писал в стиле, отличном от того английского языка, который мы привыкли читать, и это делает упражнение по генерированию текстов особенно интересным, ведь если вы незнакомы с языком Шекспира, с тем, как он устроен, то тот язык, который сгенерирует нейросеть, возможно, будет похож на оригинал. Но если бы вы жили в 1600-е годы, когда творил Шекспир, то, возможно, вы смогли бы определить, что этот текст сгенерирован нейросетью. Но в наши дни этот язык — чуть иная версия английского, и это действительно интересный сценарий. Это действительно занимательное применение нейросетей. Одним из моих любимых учителей в старшей школе была учитель английского, который заставил меня выучить многое из Шекспира, и хотелось бы мне знать, что бы она обо всём этом подумала. Да, у меня та же история. Я в старшей школе играл Генриха IV. Я даже... "Я всем вам знаю цену, но пока Потворщик первый вашим безобразиям." Я даже помню. Я так не смогу. Итак, чтобы научиться делать все эти занимательные вещи, — переходите к следующему видео.

2(w4)-video2: Introduction (17.MLg_3c)

We've seen classification of text over the last few lessons. But what about if we want to generate new text. Now this might sound like new unbroken ground, but when you think about it, you've actually covered everything that you need to do this already. Instead of generating new text, how about thinking about it as a prediction problem. Remember when for example you had a bunch of pixels for a picture, and you trained a neural network to classify what those pixels were, and it would predict the contents of the image, like maybe a fashion item, or a piece of handwriting. Well, text prediction is very similar. We can get a body of texts, extract the full vocabulary from it, and then create datasets from that, where we make it phrase the Xs and the next word in that phrase to be the Ys. For example, consider the phrase, Twinkle, Twinkle, Little, Star. What if we were to create training data where the Xs are Twinkle, Twinkle, Little, and the Y is star. Then, whenever neural network sees the words Twinkle, Twinkle, Little, the predicted next word would be star. Thus given enough words in a corpus with a neural network trained on each of the phrases in that corpus, and the predicted next word, we can come up with some pretty sophisticated text generation and this week, you'll look at coding that.
---------------------------------------------------------------
Последние несколько уроков мы имели дело с классификацией текстов. Но что, если мы захотим сгенерировать новый текст? Это может выглядеть как новое непаханое поле. Но если поразмыслить об этом, то мы уже изучили всё, что требуется, чтобы это сделать. Что, если посмотреть на это не как на порождение нового текста, а как на задачу предсказания? Вспомните, как, к примеру, вы брали пиксели, составлявшие картинку, и обучали нейросеть определять, что на этих пикселях, и она предсказывала, что на изображении: скажем, предмет одежды или письменные знаки. Предсказание текста очень похоже. У нас есть некоторый корпус текстов, мы строим по нему полный словарь, а затем создаём из него набор данных, где фразы будут за X, а следующее слово во фразе — за Y. Возьмём, например, фразу: "Чижик-пыжик, где ты был?" Что, если построить тренировочный набор, где X — это "Чижик-пыжик, где ты", а Y — "был"? И когда нейросеть увидит слова "Чижик-пыжик, где ты", она предскажет, что следующее слово — "был". Если у нас в корпусе достаточно много слов, и нейросеть обучена на каждой фразе из этого корпуса, предсказывая следующее слово, — то у нас может выйти довольно продвинутый генератор текстов. И на этой неделе вы посмотрите, как его закодировать.

3(w4)-video3: Looking into the code (17.MLg_3c)

So let's start with a simple example. I've taken a traditional Irish song and here's the first few words of it, and here's the beginning of the code to process it. In this case to keep things simple, I put the entire song into a single string. You can see that string here and I've denoted line breaks with \n. Then, by calling the split function on \n, I can create a Python list of sentences from the data and I'll convert all of that to lowercase. Using the tokenizer, I can then call fit_on_texts to this corpus of work and it will create the dictionary of words and the overall corpus. This is a key value pair with the key being the word and the value being the token for that word. We can find the total number of words in the corpus, by getting the length of its word index. We'll add one to this, to consider outer vocabulary words.
---------------------------------------------------------------
Давайте начнём с простого примера. Я взял ирландскую народную песню, и вот первые её слова. А вот первая часть кода для её обработки. В этом случае, чтобы не усложнять, я поместил всю песню в одну строку. Вот эта строка, где я обозначил переводы строк \n Вызовом функции split с параметром "\n" я могу сформировать в Python список предложений по этим данным, переведя их в нижний регистр. Используя токенизатор, я могу вызвать на этом корпусе fit_on_texts, и это даст мне словарь всех слов данного корпуса. Это пары ключ-значение, где ключом будет слово, а значением — его токен. Можно узнать общее число слов в корпусе, взяв длину словаря. Добавим к ней единицу, чтобы учесть токен для слов вне словаря.

4(w4)-video4: Preparing the training data (17.MLg_3c)

So now, let's look at the code to take this corpus and turn it into training data. Here's the beginning, I will unpack this line by line. First of all, our training x's will be called input sequences, and this will be a Python list. Then for each line in the corpus, we'll generate a token list using the tokenizers, texts to sequences method. This will convert a line of text like, "In the he town of Athy one Jeremy Lanigan," into a list of the tokens representing the words. Then we'll iterate over this list of tokens and create a number of n-grams sequences, namely the first two words in the sentence or one sequence, then the first three are another sequence etc. The result of this will be, for the first line in the song, the following input sequences that will be generated. The same process will happen for each line, but as you can see, the input sequences are simply the sentences being broken down into phrases, the first two words, the first three words, etc. We next need to find the length of the longest sentence in the corpus. To do this, we'll iterate over all of the sequences and find the longest one with code like this. Once we have our longest sequence length, the next thing to do is pad all of the sequences so that they are the same length. We will pre-pad with zeros to make it easier to extract the label, you'll see that in a few moments. So now, our line will be represented by a set of padded input sequences that looks like this. Now, that we have our sequences, the next thing we need to do is turn them into x's and y's, our input values and their labels. When you think about it, now that the sentences are represented in this way, all we have to do is take all but the last character as the x and then use the last character as the y on our label. We do that like this, where for the first sequence, everything up to the four is our input and the two is our label. Similarly, here for the second sequence where the input is two words and the label is the third word, tokenized to 66. Here, the input is three words and the label is eight, which was the fourth word in the sentence. By this point, it should be clear why we did pre-padding, because it makes it much easier for us to get the label simply by grabbing the last token.
---------------------------------------------------------------
Теперь давайте посмотрим на код, который берёт этот корпус, и превращает его в тренировочный набор данных. Вот начало, я разберу его построчно. Во-первых, X из тренировочного набора будут называться input_sequences, и это будет Python-список. Далее для каждой строки в корпусе мы сгенерируем список токенов, используя метод токенизатора texts_to_sequences. Это преобразует строку текста вроде: "In the he town of Athy one Jeremy Lanigan" — в список токенов, представляющих слова. Затем мы пройдём в цикле по всему списку токенов и создадим подпоследовательности а именно: первые два слова в предложении станут первой подпоследовательностью, затем первые три станут второй подпоследовательностью, и т. д. В результате, для первой строки песни будут сгенерированы такие входные последовательности. То же самое сделаем с каждой строкой. Но, как видите, исходные последовательности — это просто предложения, разбитые на фразы: первые два слова, первые три слова, и т. д. Затем нам надо найти длину самого длинного предложения в корпусе. Для этого мы пройдём в цикле по всем предложениям, и найдём самое длинное с помощью такого кода. Теперь, получив наибольшую длину, следующим шагом мы дополняем все последовательности до этой длины, чтобы длина была у всех одинакова. Мы дополним их нулями спереди, чтобы было проще получить метки. Скоро вы это увидите. Итак, теперь строка представлена множеством дополненных последовательностей, которые выглядят примерно так. Получив последовательности, нам дальше следует разделить их на X и Y — входные значения и их метки. Если подумать немного, то когда предложения уже представлены таким способом, нам для разметки нужно лишь взять за X всё, кроме последнего токена, а последний токен взять за Y, т.е., метку. Вот таким образом: для первого предложения все токены от начала и по "четвёрку" — наши входные данные, а 2 — метка. И аналогично для второй последовательности: вход — два слова, а метка — третье, токеном для которого будет 66. Далее на вход пойдут три слова, и меткой будет "8", которая была четвёртым словом предложения. Теперь уже должно стать ясно, почему мы дополняли спереди: потому что это намного упрощает нам получение метки — нужно лишь взять последний токен.

5(w4)-video5: More on the training data (17.MLg_3c)

So now, we have to split our sequences into our x's and our y's. To do this, let's grab the first n tokens, and make them our x's. We'll then get the last token and make it our label. Before the label becomes a y, there's one more step, and you'll see that shortly. Python makes this really easy to do with it's less syntax. So to get my x's, I just get all of the input sequences sliced to remove the last token. To get the labels, I get all of the input sequence sliced to keep the last token. Now, I should one-hot encode my labels as this really is a classification problem. Where given a sequence of words, I can classify from the corpus, what the next word would likely be. So to one-hot encode, I can use the Keras utility to convert a list to a categorical. I simply give it the list of labels and the number of classes which is my number of words, and it will create a one-hot encoding of the labels. So for example, if we consider this list of tokens as a sentence, then the x is the list up to the last value, and the label is the last value which in this case is 70. The y is a one-hot encoded array whether length is the size of the corpus of words and the value that is set to one is the one at the index of the label which in this case is the 70th element. Okay. You now have all of the data ready to train a network for prediction. Hopefully, this was useful for you. You'll see the neural network in the next video.
---------------------------------------------------------------
Итак, теперь мы должны разделить наши последовательности на X и Y. Чтобы сделать это, давайте возьмём первые несколько токенов и сделаем их X. Затем возьмём последний токен и сделаем его меткой. Прежде чем использовать эти метки как Y, мы сделаем ещё один шаг, который вы скоро увидите. Python позволяет всё очень упростить благодаря своему синтаксису для работы со списками. Чтобы взять мои X, я просто беру срез для всех входных последовательностей, отрезая от них последний токен. А чтобы получить метки, я беру такой срез у всех входных последовательностей, чтобы остался только последний токен. И теперь мне нужно сделать унитарное кодирование моих меток, т.к. у нас задача классификации. Т.к. по заданной последовательности слов я классифицирую на основе корпуса текстов, каким окажется следующее слово. Для унитарного кодирования я могу использовать утилиту из Keras, превращающую список в категориальное значение. Я просто передаю список меток и количество классов, которое совпадает с количеством слов, — и она выполняет унитарное кодирование меток. Например, если взять в качестве предложения такой список токенов, то X — это список до последнего значения, а метка — последнее значение, в данном случае, это 70. Y — код, полученный унитарным кодированием, где длина равна размеру корпуса слов, а значение 1 имеет лишь тот элемент, номер которого совпадает со значением метки, в данном случае, это 70-й элемент. Хорошо, теперь у вас есть все необходимые данные, чтобы научить сеть предсказывать. Надеюсь, вы извлекли для себя пользу. Саму нейросеть вы увидите в последующем видео. Но сперва посмотрите, как происходит предварительная обработка данных при помощи методов, которые вы увидели в этом уроке.

6(w4)-video6: Finding what the next word should be (17.MLg_3c)

In the previous video we looked at the data, a string containing a single song, and saw how to prepare that for generating new text. We saw how to tokenize the data and then create sub-sentence n-grams that were labelled with the next word in the sentence. We then one-hot encoded the labels to get us into a position where we can build a neural network that can, given a sentence, predict the next word. Now that we have our data as xs and ys, it's relatively simple for us to create a neural network to classify what the next word should be, given a set of words. Here's the code. We'll start with an embedding layer. We'll want it to handle all of our words, so we set that in the first parameter. The second parameter is the number of dimensions to use to plot the vector for a word. Feel free to tweak this to see what its impact would be on results, but I'm going to keep it at 64 for now. Finally, the size of the input dimensions will be fed in, and this is the length of the longest sequence minus 1. We subtract one because we cropped off the last word of each sequence to get the label, so our sequences will be one less than the maximum sequence length. Next we'll add an LSTM. As we saw with LSTMs earlier in the course, their cell state means that they carry context along with them, so it's not just next door neighbor words that have an impact. I'll specify 20 units here, but again, you should feel free to experiment. Finally there's a dense layer sized as the total words, which is the same size that we used for the one-hot encoding. Thus this layer will have one neuron, per word and that neuron should light up when we predict a given word. We're doing a categorical classification, so we'll set the laws to be categorical cross entropy. And we'll use the adam optimizer, which seems to work particularly well for tasks like this one. Finally, we'll train for a lot of epoch, say about 500, as it takes a while for a model like this to converge, particularly as it has very little data. So if we train the model for 500 epochs, it will look like this.
---------------------------------------------------------------
В прошлом видео мы работали с данными, состоящими из одной строки с песней, — и посмотрели, как подготовить данные для генерации нового текста. Мы увидели, как токенизировать данные и создавать подпоследовательности слов, выбирая для них в качестве метки следующее слово в предложении. Затем мы производили унитарное кодирование меток, чтобы можно было построить нейросеть, которая предсказывала бы следующее слово для заданной фразы. Располагая данными в виде X и Y, относительно просто создать нейросеть, которая по набору слов скажет, какое слово будет следующим. Вот этот код. Мы начнём со слоя эмбеддинга. Нам нужно обработать все слова, и это указано в первом параметре. Второй параметр — необходимая размерность векторов, соответствующих словам. Не стесняйтесь покрутить этот параметр, чтобы посмотреть, как он влияет на результат, но пока я оставлю его равным 64. И, наконец, последний параметр — длина входной последовательности, она на 1 меньше, чем длина самого длинного предложения. Мы вычли единицу, потому что ранее отрезали последнее слово в каждом предложении, чтобы получить метку, так что наши последовательности будут на единицу короче максимальной длины предложений. Дальше мы добавляем LSTM. Как мы уже узнали в этом курсе, вектор состояния LSTM может донести контекст не только до соседних слов, но и на всю длину последовательности. Я выделю на вектор 20 ячеек, но, опять-таки, поэкспериментируйте, меняя этот параметр. И, наконец, полносвязный слой, размер которого равен общему числу слов, и этот же размер мы использовали для унитарного кодирования. Таким образом, в этом слое будет по одному нейрону на слово, и этот нейрон будет возбуждаться, когда мы предсказываем конкретное слово. Эта сеть выполняет категориальную классификацию, так что функция потерь должна быть categorical_crossentropy. И мы используем оптимизатор adam, который, кажется, особенно хорошо подходит для таких задач. Наконец, мы должны обучаться очень много эпох, например, 500, т.к. требуется время, чтобы подобная модель должна сойтись, в частности, при столь малом объёме данных. Если обучать модель в течение 500 эпох, мы получим подобный результат.

7(w4)-video7: Example (17.MLg_3c)

Here are a few phrases that were generated when I gave the neural network the sentence Lawrence went to Dublin, and I asked it to predict the next 10 words. We'll see the code for that in a moment, but notice that there's a lot of repetition of words. In this sentence, three of the last five words are wall, and here three of the last four are ball, and even in this one the word relations gets repeated. This is because our LSTM was only carrying context forward. Let's take a look at what happens if we change the code to be bidirectional. By adding this line simply defining the LSTM is bidirectional, and then retraining, I can see that I do converge a bit quicker as you'll see in this chart. After training and testing, I now get these sentences. They make a little bit more sense, but there's still some repetition. That being said, remember this is a song where words rhyme such as ball, all and wall, et cetera, and as such many of them are going to show up.
---------------------------------------------------------------
Вот некоторые из фраз, сгенерированных, когда я задал начало предложения "Lawrence went to Dublin" и попросил предсказать следующие 10 слов. Очень скоро мы увидим сам код, но обратите внимание, что тут очень много слов повторяется. В первом предложении 3 из 5 последних слов — "wall", а во втором 3 из 4 последних — "ball", и в последнем тоже есть повтор, слово "relations". Это произошло потому, что наша LSTM передавала контекст только вперёд. Давайте посмотрим, что произойдёт, если мы изменим слой на двунаправленный. Исправив эту строку, чтобы LSTM объявлялась как двунаправленная, а затем обучив сеть заново, я обнаружил, что сеть начала сходиться быстрее, как видно на этом графике. После обучения и тестирования я получил такие предложения. Выглядит несколько более осмысленно, но всё равно есть повторения. Стоит напомнить, что это была песня, где слова рифмуются — например, "ball", "all" и "wall" и т.д.. Поэтому их и появляется так много.

8(w4)-video8: Predicting a word (17.MLg_3c)

So now, let's take a look at how to get a prediction for a word and how to generate new text based on those predictions. So let's start with a single sentence. For example, 'Lawrence went to Dublin.' I'm calling this sentence the seed. If I want to predict the next 10 words in the sentence to follow this, then this code will tokenizer that for me using the text to sequences method on the tokenizer. As we don't have an outer vocabulary word, it will ignore 'Lawrence,' which isn't in the corpus and will get the following sequence. This code will then pad the sequence so it matches the ones in the training set. So we end up with something like this which we can pass to the model to get a prediction back. This will give us the token of the word most likely to be the next one in the sequence. So now, we can do a reverse lookup on the word index items to turn the token back into a word and to add that to our seed texts, and that's it. Here's the complete code to do that 10 times and you can tweak it for more. But do you know that the more words you predict, the more likely you are going to get gibberish? Because each word is predicted, so it's not 100 per cent certain, and then the next one is less certain, and the next one, etc. So for example, if you try the same seed and predict 100 words, you'll end up with something like this. Using a larger corpus will help, and then the next video, you'll see the impact of that, as well as some tweaks that a neural network that will help you create poetry.
---------------------------------------------------------------
Итак, посмотрим теперь, как получить предсказание для слова, и как сгенерировать новый текст, основываясь на этих предсказаниях. Давайте начнём с одного предложения. Например, "Lawrence went to Dublin". Я назову это предложение порождающим. Чтобы предсказать следующие 10 слов, следующие за этими в предложении, сначала этот код токенизирует предложение, используя метод токенизатора text_to_sequences. И поскольку у нас нет специального токена для слов не из словаря, то он проигнорирует слово Lawrence, которого нет в корпусе, и получит такую последовательность. Далее вот этот код дополнит последовательность так, чтобы её длина совпадала с длиной предложений из тренировочного набора. В итоге мы получим что-то подобное, и мы сможем передать эти данные в модель, чтобы получить предсказание. Вот этот код даст нам токен слова, которое с наибольшей вероятностью должно стоять следом. И теперь можно провести обратный поиск по словарю, чтобы обратить токен в слово и добавить его к порождающему тексту. Вот и всё! Вот полный код, который всё это делает 10 раз, и вы можете изменить его, чтобы было больше итераций. Но учтите, что чем больше слов вы предсказываете, тем вероятнее в итоге получить ахинею. Ведь каждое слово прогнозируется, и уверенность прогноза — меньше 100%. И уверенность в следующем слове ещё меньше, а в следующем за ним — ещё, и т. д.. Например, если вы попробуете с той же исходной фразой предсказать 100 слов, то получите что-то вроде этого. Помочь здесь может использование большого корпуса, и в следующем видео вы увидите, как это влияет, а заодно и несколько модификаций, с помощью которых сеть поможет вам писать стихи.

9(w4)-Check out the code! (Lab 1): (17.MLg_3c)

Here is the first notebook for this week.
---------------------------------------------------------------
C3_W4_Lab_1.ipynb
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/ungraded_labs/C3_W4_Lab_1.ipynb

10(w4)-video9: Notebook for lesson 1 (17.MLg_3c)

So here's the notebook with the basic data for a single song and traditional Irish music. Later we're going to do a corpus with lots of songs. But let's take a look at what happens with just a single song just to keep it very simple. First of all, I'm just gonna input everything that I need, and now I'm going to tokenize the data from the song. We can see the data is just this one long string with all of the lyrics. I split the lines with just the /n. So when I'm creating the corpus, i am just taking that and splitting it by a /n. Tokenizer fit on text corpus will then fit a tokenizer to all the text that's in here, and we can see the actual word index replied all etc. This number 263 is the total number of unique words that are in this corpus. So it's not a lot of words of course, as we start doing predictions based off this we're going to have a very limited dataset. So we'll see a lot of gibberish but the structure will actually work quite well. So now, I am going to create my input sequences. So my training data, that I'm going to use in the entraining the neural network itself. So what I want to do is that for each sentence, in the song or in the corpus, I'm going to take a look at each of the phrases within that and then the word that actually follows. So for example, if you look at the first sentence here in the song that's in the town of Athy one Jeremy Lanigan. When I go down here to look at the tokenizers word index for those in the town of a Athy one Jeremy Lanigan, we see that those are four, two, 66, eight etc. The important one to look at here is Lanigan which is number 70. So now if I start looking at my Xs that I've created. So my training data from my Xs that I've created. Here is one sentence that's in there. It's 4, 2, 66, 8, 67, 68, 69 which is in the town of a Athy one Jeremy. So in this case we say when our training data looks like this, we want to label it with the next word in the sequence. The next word in the sequence is 70. But we've one-hot encoded that as you can see here, with The tf.keras.utils dot to categorical. So by one-hot encoding that, when we look here we see there's a one hiding in here somewhere and it's right there. That's actually the 70th elements in the list. So our labeled for that word is a one-hot encoded to the say number 70. So when we see, when we train for sequence like this, we're saying this is what it's labeled will look like. So again, if I just print these out I get four, two, 66, eight, 67, 68 it should be followed by 70 but that's not one-hot encoded to this. So that's what my training data looks like. So now, I'm going to build a model to actually train it with that data. I'm just going to create a very simple one. It's in sequential am putting an embedding in there, am feeding the embedding the total number of words and am just going to just plot them in 64 dimensions. I'm going to create a very simple lstm, bidirectional LSTM with 20 LSTM units and then I'm going to add a dense layer between that and add at the end for the total number of words activate that by softmax. So, there are 263 total words in the corpus and we're going to train for those. So my label like he said, one-hot encoded looking like this. So that will be my last layer. I'm going to compile this it's categorical. So I'm going to use categorical cross entropy. I'm just going to use the basic atom as the optimizer. Because there's not a lot of data, I'm going to have to train it quite a lot of epochs and you'll see as I start training that my accuracy is very low to begin with, but it will improve over time.
There's not a lot of data here. It's only taking about one second as you can see for each epoch and it's increasing steadily epoch by epoch.
We can see now that we're reaching the end of it. We're in the 480 epochs that the accuracy is up into the 94,95 percent range so it's looking pretty good. We actually hit that much earlier as we'll see when we chart it, but we end up with 94.7 percent accuracy. If I charted out and plot that, we'll see we kind of hit that at around 200 epochs. We probably didn't need to go all 500 but it's nice to see it training like that. So now let's take a look at predicting words using the model that we trained on this. So if I seeded with this text Lawrence went to Dublin, I am going to ask it for the next 100 words. What it's going to do, is for each of the next 100 words it's going to create a token lists using tokenizer text sequences of the seed text. Then that token list is going to get padded to the actual length that we want. Then that's going to be passed into the model. So we're going to predict the classes for the token list that was generated off of this seed text and then we'll get an output word from that. Then that will be used to feed into the next time round to predict again to get another model. So when we start with Lawrence went to Dublin, it'll get us another word and that phrase will generate another word and that phrase will generate another word etc. So if I print that out, we'll get something like this. We can see what's actually happening here is that in the beginning it kind of looks pretty good. It's beginning to make sense. But of course because our body of texts is pretty small and each prediction is a probability, as you get further and further and further then the probabilities are decreasing and the quality of the prediction as a result goes down. So you end up with for example repeated words coming from these training words. So that's a very simple example. In the next lesson, you are going to be using a much bigger corpus of text and hopefully, the predictions will make a little bit more sense and be a little bit more poetic.
---------------------------------------------------------------
Это блокнот, где подготовлены данные на основе одной ирландской народной песни. Позже мы сделаем корпус, содержащий множество песен. Но сейчас давайте посмотрим, что будет в случае всего одной песни, чтобы пока не усложнять. Во-первых, я импортирую всё, что мне нужно. Теперь я токенизирую песню. Мы видим, что данные — это одна длинная строка, где все слова песни. Я разбил песню на строки символами \n. Так что при создании корпуса я просто разбиваю входные данные по \n. Далее метод токенизатора fit_on_texts с параметром corpus обучит токенизатор на всех имеющихся текстах, и далее мы видим получившийся словарь: "replied", "all", и так далее. 263 — это общее число уникальных слов в корпусе. Разумеется, в этом корпусе не так уж много слов, и мы начинаем предсказывать, располагая очень небольшим набором данных. Так что мы увидим много ерунды, но сама структура при этом будет довольно хороша. Итак, сейчас я создам мои входные последовательности. Т.е., тренировочные данные, которые я буду использовать при обучении нейросети. Так что мне нужно для каждого предложения в этой песне, или корпусе, посмотреть на каждую содержащуюся в них фразу, а также на слово, которое за этой фразой следует. Например, если взять первое предложение в песне, то есть: "In the town of Athy one Jeremy Lanigan" — то я иду вниз, чтобы посмотреть на индексы слов в словаре токенизатора для "In the town of Athy one Jeremy Lanigan". и видно, что это будут: 4, 2, 66, 8, и т. д. Важно заметить, что здесь у слова Lanigan номер 70. Если теперь посмотреть на те X, которые я создал, на X тренировочных данных. Вот одно предложение оттуда. Это 4, 2, 66, 8, 67, 68, 69 — "In the town of Athy one Jeremy". В данном случае, мы говорим, что когда наши тренировочные данные выглядят так, то меткой должно быть следующее слово в последовательности. А следующее слово — это 70. Но мы, как видите, применили к нему унитарное кодирование с помощью tf.keras.utils.to_categorical. И закодировав это значение, при просмотре мы видим, что где-то прячется единица, вот она. А именно, в 70-м элементе списка. Итак, наша метка для этого слова закодирована единицей в 70-й позиции. И когда мы обучаем на такой последовательности, то говорим, что на выходе метка должна быть такова. Аналогично, если я просто выведу это, то получу 4, 2, 66, 8, 67, 68 и за ними должно следовать 70, но оно закодировано вот в таком виде. Итак, вот как выглядят мои тренировочные данные. Теперь я построю модель, чтобы наконец обучить её на этих данных. Я создам очень простую модель: последовательные слои, первым идёт эмбеддинг, в который подаётся общее количество слов, и я собираюсь поместить их в 64-мерное пространство. Я создам очень простую LSTM, двунаправленную, с 20 элементами, а затем добавлю полносвязный слой после LSTM, в конец сети, с выходным размером, равным числу слов, и softmax в качестве функции активации. Итак, в корпусе всего 263 слова, и мы обучим сеть на них. Мои метки, как я уже сказал, подвергаются унитарному кодированию, и выглядят примерно так. Это будет мой последний слой. Я скомпилирую модель — она категориальная, так что я использую функцию потерь categorical_crossentropy. Оптимизатором возьму базовый Adam. И т.к. данных здесь немного, я поставлю довольно большое число эпох обучения, и вы увидите, что при запуске обучения точность начнёт с низких величин, но с течением времени будет улучшаться.
Данных здесь не очень много. Как видите, 1 эпоха обучения занимает всего порядка секунды, и точность постоянно увеличивается, эпоха за эпохой.
И вот мы приближаемся к концу, мы уже на 480-й эпохе, и точность выросла до 94-95%, что выглядит неплохо. На самом деле, как мы увидим на графике, это произошло намного раньше. Но в итоге мы получили точность 94.7%. Если теперь построить график, то мы увидим, что это значение держится в течение примерно 200 эпох. Возможно, не нужно было обучать все 500 эпох, но приятно видеть, что оно обучается так. А теперь давайте посмотрим, как модель, которую мы обучили, предсказывает слова. Если я инициирую её текстом "Lawrence went to Dublin", и спрошу про следующие 100 слов, Дальше будет вот что: для каждого из следующих 100 слов я создам список токенов, используя метод токенизатора text_to_sequences и передав в него начальный текст. Затем этот список токенов надо дополнить до нужной длины, после чего передать в модель. Мы собираемся предсказать классы по списку токенов, который был создан из этого начального текста, а затем мы преобразуем их в выходное слово. И далее его можно использовать, чтобы передать на вход модели в следующий раз, чтобы предсказать снова, и получить новое предсказание модели. Итак, мы начали с Lawrence went to Dublin, это даст нам другое слово, и суммарная фраза породит ещё одно слово, и новая фраза породит другое слово, и т.д. И если распечатать результат, то мы получим что-то вроде этого: Мы видим, что, на самом деле, поначалу всё выглядело довольно неплохо. Сначала был смысл. Но из-за того, разумеется, что наш корпус очень мал, и каждое предсказание — вероятностное, чем дальше и дальше вы заходите, тем слабее шансы, и качество предсказаний в результате ухудшается. И в итоге у вас идут, к примеру, повторяющиеся слова из обучающего набора. Это был очень простой пример. На следующем занятии вы используете корпус текстов намного большего размера, и, надеюсь, предсказания станут несколько более осмысленными и несколько более поэтичными.

11(w4)-video10: Poetry! (17.MLg_3c)

In the previous video, we used the single song to generate text. We got some text from it but once we tried to predict beyond a few words, it rapidly became gibberish. So in this video, we'll take a look at adapting that work for a larger body of words to see the impact. The good news is that it will require very little code changes, so you'll be able to get it working quite quickly. I've prepared a file with a lot of songs that has 1,692 sentences in all to see what the impact would be on the poetry that a neural network would create. To download these lyrics, you can use this code.
---------------------------------------------------------------
В предыдущем видео мы генерировали текст на основе всего лишь одной песни. Мы получили на её основе какой-то текст, но едва мы пытались предсказать чуть больше слов, как текст быстро становился абсурдным. И в этом видео мы посмотрим, как доработать наши результаты для более крупного корпуса слов, и посмотрим, что тогда будет. Хорошая новость в том, что потребуются очень небольшие изменения в коде, так что вы справитесь с ними довольно быстро. Я подготовил файл с большим количеством песен, в сумме 1692 предложений, — чтобы посмотреть, как это отразится на той поэзии, которую будет создавать нейросеть. Чтобы скачать тексты, можете использовать эту строчку кода.

12(w4)-Link to the dataset: (17.MLg_3c)

You can find the dataset of Irish song lyrics here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/misc/Laurences_generated_poetry.txt
---------------------------------------------------------------

13(w4)-video11: Looking into the code (17.MLg_3c)

Now instead of hard-coding the song into a string called data, I can read it from the file like this. I've updated the model a little bit to make it work better with a larger corpus of work but please feel free to experiment with these hyper-parameters. Three things that you can experiment with. First, is the dimensionality of the embedding, 100 is purely arbitrary and I'd love to hear what type of results you will get with different values.
Similarly, I increase the number of LSTM units to 150. Again, you can try different values or you can see how it behaves if you remove the bidirectional. Perhaps you want words only to have forward meaning, where big dog makes sense but dog big doesn't make so much sense. Perhaps the biggest impact is on the optimizer. Instead of just hard coding Adam as my optimizer this time and getting the defaults, I've now created my own Adam optimizer and set the learning rate on it. Try experimenting with different values here and see the impact that they have on convergence. In particular, see how different convergences can create different poetry. And of course, training for different epochs will always have an impact with more generally being better but eventually you'll hit the law of diminishing returns.
---------------------------------------------------------------
Теперь вместо прописывания строки в самом коде, в переменной data, — я прочитаю её из файла вот таким образом. Я немного изменил модель, чтобы она работала лучше с большим корпусом произведений, но не бойтесь экспериментировать с гиперпараметрами. Вот три параметра, с которыми стоит поэкспериментировать. Во-первых, размерность эмбеддинга. 100 — совершенно произвольное число, и хотел бы я узнать, какие результаты получились у вас при других значениях.
Аналогично, я увеличил число ячеек LSTM до 150. И здесь вы тоже можете пробовать разные значения, или посмотреть, как сеть поведёт себя, если убрать из неё двунаправленность. Возможно, вы захотите использовать слова только при прямой передаче контекста, когда "большая собака" имеет смысл, а "собака большая" — не особо. Пожалуй, сильнее всего я изменил оптимизатор. Вместо того, чтобы жёстко задать adam в этом коде, с конфигурацией по умолчанию, я на этот раз создал отдельный объект Adam и задал ему темп обучения. Поэкспериментируйте и тут с различными значениями, и посмотрите, как они повлияют на сходимость. В частности, как в зависимости от сходимости может меняться поэзия. И, конечно, изменение числа эпох обучения всегда будет свою играть роль. Обычно, чем оно больше, тем лучше, но можно и упереться в закон убывающей отдачи.

14(w4)-video12: Laurence the poet! (17.MLg_3c)

In a co-lab with this data and these parameters, using a GPU, it typically takes about 20 minutes to train a model. Once it's done, try a a seed sentence and get it to give you 100 words. Note that there are no line breaks in the prediction, so you'll have to add them manually to turn the word stream into poetry. Here's a simple example. I used a famous quote from a very famous movie and let's see if you can recognize it. And I tried that to see what type of poem it would give me and I got this. And it almost make sense, [LAUGH] but that's poetry for you. Help me Obi-Wan Kenobi, you're my only hope. My dear and hope as I did fly with its flavors, along with all its joys. But sure I will build, love you still, gold it did join. Do mans run away cross our country, our wedding I was down to. Off holyhead wished myself down among the pigs. Played some hearty Riggs, me embarrass. Find me brother, me chambers she gave me her story. Be Irishmen to greet you lovely Molly. Gone away from me home, home to leave the old tin cans. The foreman's chain once was shining. Sky above I think I love.
---------------------------------------------------------------
Colab с этими данными и параметрами при использовании GPU обычно обучает модель около 20 минут. Когда модель обучится, подайте в неё порождающую последовательность и получите 100 следующих слов. Обратите внимание, что предсказания не используют переводы строк, так что вам прийдётся добавить их вручную, чтобы превратить поток слов в поэзию. Вот простой пример. Я использовал известную цитату из знаменитого кинофильма. Посмотрим, узнаете ли вы её. Я решил посмотреть, что за стих модель мне выдаст, и вот что я получил. И результат почти осмысленный. Вот вам стихи. Help me Obi-Wan Kenobi, you're my only hope. My dear and hope as I did fly with its flavors, along with all its joys. But sure I will build, love you still, gold it did join. Do mans run away cross our country, are wedding I was down to. Off holyhead wished meself down among the pigs. Played some hearty rigs, me embarrass. Find me brother, me chambers she gave me who stored be Irishmen to greet you lovely Molly. Gone away from me home, home to leave the old tin cans. The foreman's chain once was shining. Sky above I think I love.

15(w4)-Check out the code! (Lab 2): (17.MLg_3c)

Let's take a look at the second notebook for this week.
C3_W4_Lab_2_irish_lyrics.ipynb
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/ungraded_labs/C3_W4_Lab_2_irish_lyrics.ipynb
---------------------------------------------------------------

16(w4)-video13: Your next task (17.MLg_3c)

Now, this approach works very well until you have very large bodies of text with many many words. So for example, you could try the complete works of Shakespeare and you'll likely hit memory errors, as assigning the one-hot encodings of the labels to matrices that have over 31,477 elements, which is the number of unique words in the collection, and there are over 15 million sequences generated using the algorithm that we showed here. So the labels alone would require the storage of many terabytes of RAM. So for your next task, you'll go through a workbook by yourself that uses character-based prediction. The full number of unique characters in a corpus is far less than the full number of unique words, at least in English. So the same principles that you use to predict words can be used to apply here. The workbook is at this URL, so try it out, and once you've done, that you'll be ready for this week's final exercise.
---------------------------------------------------------------
Такой подход очень хорошо работает, если только у вас не очень большой корпус текстов с огромным количеством слов. Например, если вы попробуете взять полное собрание сочинений Шекспира, вам, вероятно, не хватит памяти, потому что унитарное кодирование меток в виде матриц производится для 31 477 элементов — таково число уникальных слов в словаре. А также будет свыше 15 миллионов последовательностей, создаваемых алгоритмом, который мы с вами видели. Итак, одни только метки потребуют многих терабайтов оперативной памяти на хранение. Так что следующей вашей задачей, над которой вы поработаете самостоятельно в рабочей тетради, будет предсказание на основе отдельных символов. Число всех уникальных символов в корпусе намного меньше, чем число всех уникальных слов, — во всяком случае, в английском языке. Те же правила, которые вы использовали для предсказания слов, можно применить и здесь. Пособие находится по этой ссылке, попробуйте с ним разобраться. Справившись с этим, вы будете готовы к финальному заданию этой недели.

17(w4)-Link to generating text using a character-based RNN: (17.MLg_3c)

Find the link to generating text using a character-based RNN here.
https://www.tensorflow.org/text/tutorials/text_generation
---------------------------------------------------------------

18(w4)- Week 4 Quiz: (17.MLg_3c)

1) When predicting words to generate poetry, the more words predicted the more likely it will and up gibberish. Why?:
1. Because the probability that each word matches an existing phrase goes down the more words you create (+)
2. Because the probability of prediction compounds, and thus increases overall
3. Because you are more likely to hit words not in the training set
4. It doesn't, the likelihood of gibberish doesn't change
2) What is a major drawback of word-based training for text generation instead of character-based generation?:
1. There is no major drawback, it's always better to do word-based training
2. Because there are fare more words in a typical corpus than characters, is is much more memory intensive (+)
3. Character based generation is more accurate because there are less characters to predict
4. Word based generation is more accurate because there is a larger body of words to draw from
3) What are the critical steps in preparing the input sequences for the prediction model?:
1. Pre-padding the subprhases sequences (+)
2. Splitting the dataset into training and testing sequences
3. Generating subphrases from each line using n_gram_SEQUENCES (+)
4. Converting the seed text to a token sequence using texts_to_sequences (-)
4) In natural language processing. predicting the next item in a sequence is a classification problem. Therefore, after creating inputs and labels from the subhrases, we on-not encode the labels. What function do we use to create on-hot encoded arrays of the labels?:
1. tf.keras.preprocessing.text.one_hot
2. tf.keras.utils.img_to_array
3. tf.keras.utils.to_categorical (+)
4. tf.keras.SequenceEnqueuer
5) True of False: When building the model, we use a sigmoid activated Dense output layer with one neuron per word that lights up when we predict a give word.:
1. True
2. False (+)

19(w4)- Lecture Notes Week 4: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

20(w4)- Programming Assignment: Predicting the next word: (17.MLg_3c)

Week 4: Predicting the next word
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/assignment/C3W4_Assignment.ipynb

21(w4)- Wrap up: (17.MLg_3c)

Over the last four weeks you've gotten a grounding in how to do Natural Language processing with TensorFlow and Keras. You went from first principles -- basic Tokenization and Padding of text to produce data structures that could be used in a Neural Network.
You then learned about embeddings, and how words could be mapped to vectors, and words of similar semantics given vectors pointing in a similar direction, giving you a mathematical model for their meaning, which could then be fed into a deep neural network for classification.
From there you started learning about sequence models, and how they help deepen your understanding of sentiment in text by not just looking at words in isolation, but also how their meanings change when they qualify one another.
You wrapped up by taking everything you learned and using it to build a poetry generator!
This is just a beginning in using TensorFlow for natural language processing. I hope it was a good start for you, and you feel equipped to go to the next level!
---------------------------------------------------------------
За последние четыре недели вы получили представление о том, как выполнять обработку естественного языка с помощью TensorFlow и Keras. Вы перешли от первых принципов — базовой токенизации и заполнения текста к созданию структур данных, которые можно было бы использовать в нейронной сети.
Затем вы узнали о встраиваниях и о том, как слова могут быть сопоставлены с векторами, а словам с похожей семантикой заданы векторы, указывающие в одинаковом направлении, что дало вам математическую модель их значения, которую затем можно было бы передать в глубокую нейронную сеть для классификации.
Оттуда вы начали узнавать о моделях последовательностей и о том, как они помогают углубить ваше понимание настроений в тексте, не только рассматривая слова по отдельности, но и как их значения меняются, когда они определяют друг друга.
Вы закончили тем, что взяли все, что узнали, и использовали это для создания генератора стихов!
Это только начало использования TensorFlow для обработки естественного языка. Я надеюсь, что это было хорошее начало для вас, и вы чувствуете себя готовым перейти на следующий уровень!

22(w4)-video14: A conversation with Andrew Ng (17.MLg_3c)

Congrats on making it to the end of this course, where you've learned a lot about how to implement models for natural language processing. But the sequence models you've learned like the RNN, the GRU, the LSTM, they're useful for even more applications specifically time-series applications. Everything from processing weather data to processing stock market data, to try and understand "EKG" electrocardiogram that's time series electric recordings of your heart. These types of models are useful, all of these applications. So in the next course, you go deeper to learn more about how to build and train such models. So like a lot of that stuff as Andrew has mentioned just that we've done with natural language processing and sequence modeling, and even other things that we've learned in this course for example, convolutions and the convolutional neural network course, are all going to be able to come together as you start doing sequences and prediction, and we think it's going to be a really, really nice module to help really just build under those skills that you've been doing and help you move towards mastery of tensorflow. These models are important and in the next course, I hope you enjoy learning about them. So please go on to the next course.
---------------------------------------------------------------
Поздравляю с окончанием этого курса, из которого вы много узнали о том, как реализовывать модели для обработки естественного языка. Но модели, подобные РНС, УРБ, LSTM, которые вы изучили, могут работать не только с языковыми последовательностями, они имеют и другие применения — например, применимы к временным рядам. К любым: от обработки погодных данных и до биржевых показателей. Можно пытаться разбирать ЭКГ — электрокардиограмму, запись серии электрических импульсов вашего сердца. Подобные модели полезны в каждом из этих случаев. Так что в следующем курсе вы подробнее изучите, как строить и обучать такие модели. Эндрю уже о многом сказал: о том, что наши наработки в обработке естественных языков и в моделировании последовательностей, а также многое другое, чему мы научились в этом курсе — например, свёрткам и свёрточным нейросетям, — всё это, разумеется, можно объединить при работе с последовательностями и их предсказанием. И мы думаем, что это будет действительно хороший модуль, помогающий распорядиться теми умениями, которые вы приобрели, и помочь вам нарабатывать мастерство в использовании TensorFlow. Эти модели очень важны, и в следующем курсе, надеюсь, вы получите удовольствие, изучая их. Так что приглашаю вас перейти к следующему курсу.

22(w4)-Acknowledgments: (17.MLg_3c)

In addition to the original Curriculum Developers, the following people made significant contributions to the Course 3 refresh:


18.MLg_4c


(w1)Sequences and Prediction (18.MLg_4c)

(Последовательности и прогноз)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 31 minutes
Self-study: 1h 19 min
Graded tasks (Tasks to be assessed): 2

(w1) Content (18.MLg_4c)

1. 2. 3. 4.

(w1) Introduction: (18.MLg_4c)

Hi Learners and welcome to this course on sequences and prediction! In this course we'll take a look at some of the unique considerations involved when handling sequential time series data -- where values change over time, like the temperature on a particular day, or the number of visitors to your web site. We'll discuss various methodologies for predicting future values in these time series, building on what you've learned in previous courses!
---------------------------------------------------------------
Привет, учащиеся, и добро пожаловать на этот курс по последовательностям и предсказаниям! В этом курсе мы рассмотрим некоторые уникальные моменты, связанные с обработкой последовательных данных временных рядов, где значения меняются со временем, например, температура в определенный день или количество посетителей вашего веб-сайта. Мы обсудим различные методологии прогнозирования будущих значений в этих временных рядах, основываясь на том, что вы узнали на предыдущих курсах!

1(w1)-video1: Introduction, A conversation with Andrew Ng (18.MLg_4c)

Welcome to the fourth and final course of this specialization, just one course away from finishing this whole specialization and have you learnt a lot about Tensorflow. In this course, you learned about sequence models, what are sequence models? So what we're going to be focusing on is one part of sequence models, which is really time-series. Sequence models where it's a case of if you can imagine a series of data that changes over time. It might be the closing prices for stock on the stock exchange, or it could be weather. It could be how sunny it is in California on a given day, or how rainy it is in Seattle on a given day, that type of thing. So if you just imagine how an item of data changes over time and how it's measured over time. So basically almost anything like a spreadsheet, if I've a spreadsheet where I have one day per row and two columns say one for the California weather, one for the Seattle weather to document how better my life is to yours in Seattle than in California, and then we would have a new network help us model that. Exactly. So we're going to start by creating a synthetic sequence of data, so that we can start looking at what the common attributes that you see in data series are. So for example, whether data can be seasonal. It's sunnier in June than it is in January or it's wetter in November than it is in October, something along those lines. So you have that seasonality of data. You can also, in some cases, have trends of data, like whether it probably doesn't really trend although we could argue that it strangely enough idea with climate change, but like a stock data may trend upwards over time or downwards over some other times, and then of course the random factor that makes it hard to predict is noise. So you can have like seasonal data, you can have trends in your data, but then you can have noise on that data as well. So that the average temperature of a Tuesday in June and California might be 85 degrees, but it might be 85.5 degrees, it might be 84.5 degrees. So you get that noise in the data. So we want to start looking at various methods that can be used statistically in the Machine Learning to help us predict data given seasonality trend and noise. Then in this course, at the end of this course, one of the most cool applications is to use these ideas to model sunspot. Sunspot activity. Yeah. So sunspot activity is really interesting because the sun has an 11-year cycle although some astronomers tell me it's a 22-year cycle, there's actually two 11-year cycles like nestled beside each other. Will we resolve this in this course? That remains to be seen. You're going to have to study all the way through and then we'll see, but the idea then is that you do get that nice seasonality, and we have data measuring back about 250 years worth of sunspot activity. So that's on a monthly basis counting the number of sunspots that had been spotted by astronomers. So we do definitely see that 11 year cycle or maybe the 22-year cycle, and there's a lot of noise in there, the seasonality and that stuff. So it's fun to build something to protect sunspot activity. In fact, sunspot activity is very important to NASA and other space agencies because it affects satellite operations. So in this course, you'll start by learning about sequence models, a time series data, first practicing these skills and building these models on artificial Data, and then at the end of this course, you get to take all these ideas and apply them to the exciting problem of modeling sunspot activity. So let's get started. Please go on to the next video.
---------------------------------------------------------------
Добро пожаловать в четвёртый и завершающий курс данной специализации. Вам остался лишь один курс до окончания всей специализации, и вы уже многое узнали о TensorFlow. В этом курсе вы изучите модели последовательностей. Что это за модели? Итак, мы сосредоточимся на одном виде моделей последовательностей — на временных рядах. Модели последовательностей можно представить как ряд данных, меняющийся со временем. Это может быть цена закрытия для торгов на фондовой бирже, или погодные данные. Например, насколько солнечно в Калифорнии в данный день, или сколько осадков в Сиэтле на определённую дату, вот такого рода вещи. Можно просто представить, как показатель меняется со временем, и как с течением времени ведутся измерения. То есть, это почти один в один электронная таблица: можно взять таблицу, в которой на каждой строке свой день, и два столбца: в одном погода в Калифорнии, а в другом о погоде в Сиэтле, — и фиксировать в таблице, насколько лучше моя жизнь в Сиэтле, чем ваша в Калифорнии, — а затем мы возьмём новую нейросеть, чтобы всё это смоделировать. Именно. Так что начнём с создания искусственной последовательности данных, чтобы можно было посмотреть, какие общие признаки можно выделить в рядах данных. Например, данные о погоде носят сезонный характер. В июне солнечнее, чем в январе, а погода в ноябре лучше, чем в октябре. Что-то в таком роде. Итак, в данных бывает сезонность. Также иногда можно видеть в данных тренды (тенденции) — пожалуй, в погоде трендов особо нет, хотя можно возразить, что тренд есть, если взять идею изменения климата. Но как в биржевых данных, какой-то период может наблюдаться восходящий тренд, а в другой — нисходящий. Наконец, есть, разумеется, и фактор случайности, затрудняющий предсказания шум. Итак, в данных бывает сезонность, могут присутствовать временные тренды, а также может присутствовать шум. И средняя температура в июньский четверг для Калифорнии может быть 30 градусов Цельсия, [85 по Фаренгейту - прим. пер.] но также может и 30,5 градусов, а может быть и 29,5. Так что, в данных есть шум. И мы обратимся к различным методам, которые можно применить для машинного обучения в области статистики, чтобы прогнозировать данные с учётом сезонности, трендов и шума. В этом курсе, в конце этого курса, одним из самых захватывающих приложений станет использование этих знаний для моделирования солнечных пятен. Солнечной активности, да. Солнечная активность — это очень интересно, ведь у Солнца есть 11-летний цикл, хотя некоторые астрономы говорят, что это 22-летний цикл, в котором два 11-летних цикла, идущих друг за другом. Мы разберёмся с этим вопросом в данном курсе? Это надо посмотреть. Сначала нужно изучить весь материал, а там увидим. Но идея в том, чтобы взять эту отчётливую сезонность, а у нас есть данные измерений солнечной активности на протяжении 250 лет. Это данные от ежемесячных подсчётов отмечаемых астрономами солнечных пятен. Так что мы определённо увидим этот 11-летний цикл — а может, 22-летний цикл, и в нём очень много шума, сезонность, и тому подобное. Увлекательное дело — построить инструмент для прогноза солнечной активности. Солнечная активность очень важна для NASA и других космических агентств, т.к. она влияет на работу спутников. Итак, в этом курсе, в котором вы начинаете изучать моделирование последовательностей, модели временных рядов, и сперва потренируетесь в этом, создавая модели на искусственных данных. А в конце этого курса вы возьмёте все эти идеи и примените их в захватывающей задаче моделирования солнечной активности. Итак, приступим. Приглашаем вас в следующее видео.

2(w1)-video2: Time series examples (18.MLg_4c)

Welcome to this course on sequences and prediction, a part of the TensorFlow in practice specialization. In this course, we'll focus on time series, where you'll learn about different types of time series before we go deeper into using time series data. This week, you'll focus on time series themselves. We'll go through some examples of different types of time series, as well as looking at basic forecasting around them. You'll also start preparing time series data for machine learning algorithms. For example, how do you split time series data into training, validation, and testing sets? We'll explore some best practices and tools around that to get you ready for week 2, where you'll start looking at forecasting using a dense model, and how it differs from more naive predictions based on simple numerical analysis of the data. In week 3, we'll get into using recurrent neural networks to forecast time series. We'll see the stateless and stateful approaches, training on windows of data, and you'll also get hands-on in forecasting for yourself. Finally, in week 4, you'll add convolutions to the mix and put everything you've worked on together to start forecasting some real world data, and that's measurements of sunspot activity over the last 250 years. So let's get started with a look at time series, what they are, and the different types of them that you may encounter. Time series are everywhere. You may have seen them in stock prices, weather forecasts, historical trends, such as Moore's law. Here, I've plotted the number of transistors per square millimeter, where I grouped chip releases by year, and then drew the Moore's law trend line from the first data item, where you can see a correlation. If you want some really fun correlations, here's one from Tyler Vigen's site of Spurious Correlations. This one is a time series correlation of total revenue generated by video game arcades versus computer science doctorates awarded in the United States. While all of these are quite familiar, they begged the question, what exactly is a time series? It's typically defined as an ordered sequence of values that are usually equally spaced over time. So for example, every year in my Moore's law charts or every day in the weather forecast. In each of these examples, there is a single value at each time step, and as a results, the term univariate is used to describe them. You may also encounter time series that have multiple values at each time step. As you might expect, they're called Multivariate Time Series. Multivariate Time Series charts can be useful ways of understanding the impact of related data. For example, consider this chart of births versus deaths in Japan from 1950 to 2008. It clearly shows the two converging, but then deaths begin to outstrip births leading to a population decline. Now, while they could be treated as two separate univariate time series, the real value of the data becomes apparent when we show them together as a multivariate. Also consider this chart showing the global temperature against CO2 concentration. As univariates, they would show a trend, but when combined, the correlation is very easy to see adding further value to the data. Movement of a body can also be plotted as a series of univariates or as a combined multivariate. Consider, for example, the path of a car as it travels. A time step zero is at a particular latitude and longitude. As subsequent time steps, these values changed based on the path of the car. The acceleration of the car, in other words, it's not moving at a constant speed, means that the spaces between the time steps also change in size, in this case getting larger. But what if we were to plot the direction of the car as univariates. Based on its heading, we could see that the longitude of the car decreases over time, but its latitude increases, and as such you will get charts like these.
---------------------------------------------------------------
Добро пожаловать в этот курс, посвящённый последовательностям и прогнозированию, часть специализации "TensorFlow на практике". В этом курсе мы сосредоточимся на временных рядах. Вы узнаете о разных типах временных рядов, прежде чем углубиться в работу с такими данными. На этой неделе мы сфокусируемся на самих временных рядах. Мы пройдёмся по нескольким примерам временных рядов разных типов и посмотрим на базовое прогнозирование их значений. Вы также познакомитесь с подготовкой временных рядов для алгоритмов машинного обучения. Узнаете, например, как разделять данные временных рядов на тренировочный, валидационный и тестовый наборы. Мы изучим передовой опыт и инструменты в этой части, чтобы вы были готовы ко второй неделе, когда мы займёмся прогнозированием с использованием полносвязных моделей, и посмотрим, чем это отличается от более наивных прогнозов, основанных на простом численном анализе данных. На третьей неделе мы погрузимся в использование рекуррентных нейросетей для предсказания временных рядов. Мы посмотрим на подходы с сохранением состояния и без сохранения состояния, а также обучение на окне данных. И вы попрактикуетесь в предсказаниях самостоятельно. Наконец, на четвёртой неделе вы добавите к своему ассортименту свёртки, и сведёте воедино то, над чем вы работали, чтобы предсказывать уже реальные данные. Это будут измерения солнечной активности за последние 250 лет. Итак, давайте начнём с рассмотрения временных рядов: что они из себя представляют, и с какими различными их типами вы можете столкнуться. Временные ряды есть во всём вокруг. Вы могли видеть их на примере биржевых цен, прогнозов погоды, исторических трендов, таких как закон Мура. Тут я построил график числа транзисторов на квадратный миллиметр, сгруппировав чипы по годам их выпуска, а затем нарисовал линию тренда закона Мура из самой первой точки, и здесь можно видеть корреляцию. А если хотите и правда забавных корреляций, то вот одна, с сайта иллюзорных корреляций Тайлера Вигена. Это корреляция между совокупными прибылями от аркадных видеоигр — и числом присвоенных докторских степеней по информатике в США. Хотя это всё довольно знакомо, встаёт вопрос: что же такое временные ряды? Обычно их определяют как упорядоченную последовательность значений, которые обычно равномерно распределены во времени. Например, с шагом в год, как в моём графике, посвящённом закону Мура, или раз в день, в случае прогноза погоды. В каждом из этих примеров каждому шагу по времени соответствует единственное значение, а потому для их описания используется термин "одновариантный". Также вы можете столкнуться с временными рядами, имеющими по несколько значений на каждый временной интервал. Как вы можете догадаться, они называются многовариантными временными рядами. Графики многовариантных временных рядов могут быть полезны для понимания взаимосвязей в данных. Например, посмотрите на этот график рождений и смертей в Японии с 1950 до 2008 гг.. Здесь отчётливо видно, что две линии сходятся, а затем смерти начинают превалировать над рождениями, что ведёт к уменьшению населения. И, хотя можно рассматривать их как два отдельных одновариантных временных ряда, но истинное их значение проступает, когда мы показываем их вместе, как многовариантный ряд. Также посмотрите на этот график с глобальной температурой и концентрацией CO2. Если считать их одновариантными, они покажут тренд, но если их скомбинировать, то очень легко увидеть корреляцию, придающую значимости этим данным. Движение тела тоже можно изобразить как одновариантные или скомбинированные многовариантные временные ряды. Взять, например, путь едущей машины. В нулевой момент времени она находится в точке с некоторой широтой и долготой. В последующие моменты эти значения изменяются в соответствии с путём машины. Ускорение машины, или, иными словами, то, что она движется не с постоянной скоростью, — означает, что длина пройденного пути между отсечками — также меняется, в данном случае, растёт. Но что, если мы изобразим движение машины как одновариантные ряды? По направлению езды мы видим, что долгота машины уменьшается со временем, но широта растёт, и в итоге получаются вот такие графики.

3(w1)-video3: Machine learning applied to time series (18.MLg_4c)

Now these are just a few examples of the types of things that can be analyzed using time series. And just about anything that has a time factor in it can be analyzed in this way. So what types of things can we do with machine learning over time series? The first and most obvious is prediction of forecasting based on the data. So for example with the birth and death rate chart for Japan that we showed earlier. It would be very useful to predict future values so that government agencies can plan for retirement, immigration and other societal impacts of these trends. In some cases, you might also want to project back into the past to see how we got to where we are now. This process is called imputation. Now maybe you want to get an idea for what the data would have been like had you been able to collect it before the data you already have. Or you might simply want to fill in holes in your data for what data doesn't already exist. For example, in our Moore's law chart from earlier. There was no data for some years because there were no chips released in those years, and you can see the gaps here. But with imputation, we can fill them up. Additionally, time series prediction can be used to detect anomalies. For example, in website logs so that you could see potential denial of service attacks showing up as a spike on the time series like this. The other option is to analyze the time series to spot patterns in them that determine what generated the series itself. A classic example of this is to analyze sound waves to spot words in them which can be used as a neural network for speech recognition. Here for example, you can see how a sound wave is split into words. Using machine learning, it becomes possible to train a neural network based on the time series to recognize words or sub words.
---------------------------------------------------------------
Мы увидели лишь несколько примеров явлений, которые можно проанализировать с помощью временных рядов. Так можно анализировать практически всё, что связано со временем. Как же можно применить машинное обучение к временным рядам? Первое, и наиболее очевидное, — прогнозирование по имеющимся данным. Возьмём, например, график рождений и смертей для Японии, который мы уже видели. Для государственных учреждений было бы очень полезно предсказать значения в будущем, чтобы планировать по ним пенсионную и иммиграционную политику, а также иные социальные программы. В некоторых случаях может понадобиться направить предсказания на прошлое, чтобы увидеть, как мы попали в нынешнюю ситуацию. Это называется "импутация" (подстановка). Возможно, хочется понять, как могли выглядеть показатели, если бы вы начали собирать их ещё раньше. Или возможно, вы просто хотите заполнить пробелы в ваших данных, те точки, где данных нет. Например, в графике для закона Мура, который мы уже видели, для каких-то годов нет данных, потому что в эти годы не выходило новых чипов, и в таких местах видны разрывы. Но мы можем их заполнить импутацией. Кроме того, предсказание временных рядов можно использовать при поиске аномалий. Например, в логах веб-сайта, чтобы увидеть потенциальную атаку "отказ в обслуживании", проявляющуюся в виде пика в данных, похожего на этот. Ещё одна возможность — анализировать временные ряды в поиске шаблонов, позволяющих выяснить, что сгенерировало сам этот ряд. Классический тому пример — анализ звуковых волн, чтобы выделить в них слова, и на основе этого можно создать нейросеть для распознавания речи. Например, здесь показано, как волна делится на слова. Используя машинное обучение, можно обучить нейросеть, основанную на временных рядах, распознаванию слов или слогов.

4(w1)-video4: Common patterns in time series (18.MLg_4c)

Time-series come in all shapes and sizes, but there are a number of very common patterns. So it's useful to recognize them when you see them. For the next few minutes we'll take a look at some examples. The first is trend, where time series have a specific direction that they're moving in. As you can see from the Moore's Law example we showed earlier, this is an upwards facing trend. Another concept is seasonality, which is seen when patterns repeat at predictable intervals. For example, take a look at this chart showing active users at a website for software developers. It follows a very distinct pattern of regular dips. Can you guess what they are? Well, what if I told you if it was up for five units and then down for two? Then you could tell that it very clearly dips on the weekends when less people are working and thus it shows seasonality. Other seasonal series could be shopping sites that peak on weekends or sport sites that peak at various times throughout the year, like the draft or opening day, the All-Star day playoffs and maybe the championship game. Of course, some time series can have a combination of both trend and seasonality as this chart shows. There's an overall upwards trend but there are local peaks and troughs. But of course, there are also some that are probably not predictable at all and just a complete set of random values producing what's typically called white noise. There's not a whole lot you can do with this type of data. But then consider this time series. There's no trend and there's no seasonality. The spikes appear at random timestamps. You can't predict when that will happen next or how strong they will be. But clearly, the entire series isn't random. Between the spikes there's a very deterministic type of decay. We can see here that the value of each time step is 99 percent of the value of the previous time step plus an occasional spike. This is an auto correlated time series. Namely it correlates with a delayed copy of itself often called a lag. This example you can see at lag one there's a strong autocorrelation. Often a time series like this is described as having memory as steps are dependent on previous ones. The spikes which are unpredictable are often called Innovations. In other words, they cannot be predicted based on past values. Another example is here where there are multiple autocorrelations, in this case, at time steps one and 50. The lag one autocorrelation gives these very quick short-term exponential delays, and the 50 gives the small balance after each spike. Time series you'll encounter in real life probably have a bit of each of these features: trend, seasonality, autocorrelation, and noise. As we've learned a machine-learning model is designed to spot patterns, and when we spot patterns we can make predictions. For the most part this can also work with time series except for the noise which is unpredictable. But we should recognize that this assumes that patterns that existed in the past will of course continue on into the future. Of course, real life time series are not always that simple. Their behavior can change drastically over time. For example, this time series had a positive trend and a clear seasonality up to time step 200. But then something happened to change its behavior completely. If this were stock, price then maybe it was a big financial crisis or a big scandal or perhaps a disruptive technological breakthrough causing a massive change. After that the time series started to trend downward without any clear seasonality. We'll typically call this a non-stationary time series. To predict on this we could just train for limited period of time. For example, here where I take just the last 100 steps. You'll probably get a better performance than if you had trained on the entire time series. But that's breaking the mold for typical machine, learning where we always assume that more data is better. But for time series forecasting it really depends on the time series. If it's stationary, meaning its behavior does not change over time, then great. The more data you have the better. But if it's not stationary then the optimal time window that you should use for training will vary. Ideally, we would like to be able to take the whole series into account and generate a prediction for what might happen next. As you can see, this isn't always as simple as you might think given a drastic change like the one we see here. So that's some of what you're going to be looking at in this course. But let's start by going through a workbook that generates sequences like those you saw in this video. After that we'll then try to predict some of these synthesized sequences as a practice before later we'll move on to real-world data.
---------------------------------------------------------------
Временные ряды бывают всевозможных форм и размеров, но есть несколько очень распространённых шаблонов. Стоит научиться различать их при взгляде на данные. В ближайшие несколько минут мы рассмотрим некоторые примеры. Первый — это тренд, когда есть определённое направление, в котором ряд движется. Как видите на примере закона Мура, который мы показывали раньше, это — восходящий тренд. Другой случай — сезонность, которая проявляется в том, что шаблон повторяется с предсказуемой периодичностью. Например, посмотрите на этот график, отражающий число активных пользователей на сайте для программистов. В нём прослеживается отчётливый шаблон регулярных провалов. Можете угадать, что это? А если я вам скажу, что значения высоки в течение 5 единиц времени, и низкие в течение 2? Тогда вы скажете, что, очевидно, провалы приходятся на выходные, когда работает меньше людей, и это пример сезонности. Другие сезонные ряды могут наблюдаться в местах для шопинга, где резко растёт посещаемость по выходным дням, или спортивные сооружения, где наблюдаются пики в конкретные моменты в году, как драфт, день открытия сезона, игра всех звёзд, плей-офф, и, возможно, матч за чемпионство. И, конечно, в некоторых временных рядах могут сочетаться тренд и сезонность, как показано на этом графике. Тут есть общий восходящий тренд, но есть также и локальные пики и провалы. И, конечно, возможны временные ряды, которые, вероятно, не прогнозируемы вовсе, являясь лишь набором случайных величин, производящих т.н. белый шум. Мало что можно поделать с такими данными. А теперь посмотрите на этот временной ряд. Тут нет тренда, и нет сезонности. Выбросы появляются в случайные моменты времени. Вы не можете предсказать, когда произойдёт следующий и насколько сильным он будет. Но ряд, очевидно, в целом не случаен. Между выбросами он демонстрирует очень предсказуемый тип убывания. Мы видим, что значение на каждом шаге составляет 99% от значения предыдущего шага плюс случайный выброс. Это автокорреляционный временной ряд. Название подсказывает, что он коррелирует со сдвинутой по времени копией себя, которую часто называют "лаг". На этом примере видно, что сильная автокорреляция происходит при лаге 1. Часто такие временные ряды описываются как имеющие память, поскольку новый отсчёт зависит от предыдущих. Непредсказуемые выбросы часто называют инновациями. Другими словами, их нельзя предсказать, основываясь на прошлых значениях. Другой наш пример — со множественными автокорреляциями, в данном случае, с лагами 1 и 50. Автокорреляция с лагом 1 даёт очень быстрое краткосрочное экспоненциальное убывание, а с лагом 50 даёт небольшой остаток после каждого выброса. Временные ряды, которые вам встретятся в реальных задачах, возможно, будут иметь понемногу от каждого из этих шаблонов: тренд, сезонность, автокорреляция и шум. Как мы узнали, модели в машинном обучении предназначены находить шаблоны, а когда мы их обнаруживаем, то можем делать предсказания. По большей части, это же применимо и ко временным рядам — кроме шума, который непредсказуем. Но стоит сознавать: предполагается, что шаблоны, существовавшие в прошлом, сохранятся и в будущем. Конечно, реальные временные ряды не всегда такие простые. Их поведение может резко измениться в один миг. Например, этот временной ряд имел положительный тренд и отчётливую сезонность вплоть до шага 200. Но затем нечто произошло, и это полностью изменило поведение ряда. Если это биржевая цена, то, возможно, это был крупный финансовый кризис, или большой скандал, или, возможно, взрывной прорыв в технологиях, породивший масштабные перемены. И после этого временной ряд начал проявлять нисходящий тренд без явной сезонности. Мы будем называть такие временные ряды нестационарными. Чтобы предсказать его значение, мы должны обучаться лишь на ограниченном временном промежутке. Например, здесь я взял только последние 100 шагов. И в таком случае, вероятно, качество прогнозов будет выше, чем при обучении на всём временном ряде. Это ломает шаблон типичного машинного обучения, где мы всегда предполагаем, что чем больше данных, тем лучше. Для предсказания временных рядов тут всё зависит от самого временного ряда. Если он стационарный, то есть, его поведение не меняется со временем, — тогда отлично, чем больше у вас данных, тем лучше. Но если он нестационарный, тогда оптимальный интервал, который нужно использовать в обучении, — будет меняться. В идеале, нам бы хотелось принимать во внимание весь временной ряд и выдавать предсказание, что случится дальше. Но, как видите, это не всегда так просто, как можно подумать, с учётом резких изменений вроде тех, что здесь показаны. Итак, это была часть того, что вы увидите в данном курсе. Но давайте начнём с того, что посмотрим блокнот, где генерируются последовательности, подобные тем, что мы здесь видели. А затем уже постараемся предсказать некоторые из этих синтезированных последовательностей чтобы попрактиковаться, прежде чем перейти к реальным данным.

5(w1)-video5: Introduction to time series (18.MLg_4c)

Let's take a look at time series and the various attributes of time series using Python. This notebook is available as part of the course and I'll provide a link to it. I recommend that you watch this video first and then try the notebook for yourself afterwards. I'll start by running the nodes containing the imports as well as a couple of helper functions. One to plot the series and one to return a trend. So now, let's plot our first very simple time series. Even though it's a straight line, it's also an example of the time series. The x-axis in this case is time and the y value is the value of the function at that time. Next, we'll take a look at adding a seasonal pattern to our time series. These functions contain a seasonal pattern and then seasonality that just uses the same pattern. We'll now plot that. As we investigate the graph, we can see clear peaks and troughs. But in addition to that, there are smaller, regular spikes. This could be seen as a rough simulation of a seasonal value. For example, maybe profits for shop that are negative on the day the store is closed, peaking a little the day after, decaying during the week and then peaking again on the weekend. What if we now add a trend to this so that the seasonal data while still following the pattern increases over time? Maybe simulating a growing business so when we plot it, we'll see the same pattern but with an overall upward trend. What if we now add another feature that's common in time series, noise? Here's a function that add some noise to a series and when we call that and plot the results and their impact on our time series, we now get a very noisy series, but one which follows the same seasonality as we saw earlier. It's interesting because at this point, the human eye may miss a lot of the seasonality data but a computer will hopefully be able to spot it. Next we can explore a little bit of Autocorrelation, but first here are a couple of functions that can add it for you. Here is where we add the autocorrelation to the series and plot it. There are two different autocorrelation functions and I'll plot both so that you can see the effects of each. This one is particularly interesting because you can see the repeated pattern despite different scales. There is a pattern and then a sharp fall off followed by the same pattern on a smaller scale with the same fall off, which is then shrunk et cetera. If I change autocorrelation functions and run it again, we can then see the other function. Now, I'm going to add some impulses and plot them. Nothing too exciting here yet. But when I start adding some autocorrelations to this, then we'll see some of the behavior that we had discussed earlier where from our pulse we have a decay away from it but the decay could be interrupted by another pulse. This decay could be autocorrelated so that after the pulse it decays but then the decay autocorrelates. So we have these decreasing curves. Then we'll try another autocorrelation and another. Now, let's add them to simulate a seasonal time series that has an impact full of events that changes everything. For example, that might be a financial series that shows seasonality, but then something changes like a failure of the business or big news events. Hopefully this exploration of some synthetic data to show some of the attributes of time-series was helpful for you to understand some of the terminology. I have found that synthetic data like this is very useful if you want to learn how to use Machine Learning to understand and predict on data. In the next lesson, you'll take the first steps towards predicting the next values in a synthetic series before later in the course, you'll start applying what you've learned to real-world data.
---------------------------------------------------------------
Давайте поглядим на временные ряды и их различные свойства с помощью Python. Этот блокнот доступен в составе курса, и я дам ссылку на него. Рекомендую сначала посмотреть это видео, а затем уже поработать с блокнотом самостоятельно. Я начну с запуска строк, содержащих импорт библиотек и пару вспомогательных функций. Одна строит график ряда, а другая возвращает тренд. Итак, построим график первого, очень простого ряда. Пусть это и прямая линия — но это тоже пример временного ряда. По оси абсцисс отложено время, а по оси ординат — значение функции в это время. Дальше мы посмотрим, как добавить к нашему временному ряду сезонную закономерность. В этой функции заключён сезонный паттерн, и функция seasonality (сезонность) всегда использует этот паттерн. Построим её график. Изучая график, мы видим отчётливые пики и провалы. Но вдобавок к ним есть также регулярные выбросы меньшего масштаба. Это можно считать грубой имитацией сезонных изменений значений. Это может быть, например, прибыль магазина, отрицательная в тот день, когда магазин закрыт, и подскакивающая на следующий день, а затем убывающая в течение недели, и снова выходящая на пик в выходные. Что, если мы сейчас добавим сюда тренд, чтобы сезонность по-прежнему отвечала своему паттерну, но величина со временем росла? Возможно, это симуляция растущего бизнеса. Так что, построив график, мы увидим тот же шаблон, но с восходящим трендом. Что, если теперь добавить другой часто встречающийся во временных рядах элемент — шум? Вот функция, которая добавляет немного шума в ряд, и если её вызвать и вывести на график результат, то, как он влияет на наш временной ряд, — то мы получим очень зашумлённый ряд, но он, тем не менее, подчиняется той же сезонности, которую мы видели раньше. Это любопытно, ведь теперь человеческий глаз может упустить большую часть сезонной составляющей, но мы надеемся, что компьютер сумеет её заметить. Дальше можно немного поисследовать автокорреляции, но сперва добавим пару функций для её добавления в ряд. И здесь мы добавляем к ряду автокорреляцию и строим график. Тут две различных автокорреляционных функции, и я выведу обе, чтобы вы могли увидеть, как сказывается каждая из них. Эта — особенно интересная, потому что здесь виден повторяющийся шаблон, вопреки разнице в масштабе. Вот шаблон, затем резкое падение, за которым следует тот же шаблон в меньшем масштабе с таким же падением, которое уменьшается, и т. д. Если я изменю автокорреляционную функцию и запущу её опять, то мы увидим другие результаты. А теперь давайте добавим немного шума. И попробуем другую функцию автокорреляции. И ещё одну. А сейчас давайте добавим их к симуляции сезонных временных рядов, где есть важные события, меняющие всё. Например, это может быть финансовый ряд, демонстрирующий сезонность, но потом что-то меняется — например, провал в бизнесе, или важные новости. Я добавлю несколько импульсов и выведу на график. Пока ничего впечатляющего. Но когда я начинаю добавлять автокорреляцию, то мы увидим что-то, похоже на поведение, которое мы обсуждали раньше, где после всплеска значения убывают, но один всплеск может быть прерван другим. И это убывание может быть автокоррелированным, так что после всплеска идёт спад, но затем спад автокоррелирует, и у нас получаются эти нисходящие кривые. Надеюсь, такое изучение искусственных данных с целью продемонстрировать некоторые свойства временных рядов — помогло вам понять часть терминологии. Я обнаружил, что синтетические данные, подобные этим, — очень полезны, когда нужно научиться использовать машинное обучение для понимания и предсказания данных. В следующем уроке вы сделаете первые шаги к тому, чтобы предсказывать последующие значения в искусственных рядах — прежде чем переходить в рамках курса к применению ваших новых знаний к реальным данным.

6(w1)-Where to find the notebooks for this course: (18.MLg_4c)

All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You will be taken to Google Colab for the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this Github repository
under the C4 folder. If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
numpy==1.20.1
matplotlib==3.2.2
---------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы будете перенаправлены в Google Colab для невыставленных лабораторных работ, а для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом репозитории Github.
в папке C4. Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

7(w1)-Introduction to time series notebook (Lab 1): (18.MLg_4c)

Here is the link to the notebook that Laurence just showed in the previous screencast.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W1/ungraded_labs/C4_W1_Lab_1_time_series.ipynb
Ungraded Lab: Introduction to Time Series Plots
---------------------------------------------------------------

8(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community!: (18.MLg_4c)

Hello!
We’ve created a community for you to:
Ask for help on assignments and other course content.
Discuss course topics.
Share your knowledge with other learners.
Build your network
Find out about exciting DeepLearning.AI news, events and competitions!
To go to the community for this course, tick the checkbox below indicating you agree to use the app responsibly, then click on the "Launch App” button.
If you are new to the community, click on the "Launch App" button to create your account and access our community.
We created this User Guide for you. https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Be sure to check out the Code of Conduct community guidelines. https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
aving trouble accessing our community after clicking the “Launch App” button? Fill out this form to explain your issue and we will get back to you.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
---------------------------------------------------------------

9(w1)-video6: Train, validation and test sets (18.MLg_4c)

In the previous videos this week, you saw all of the different factors that make up the behavior of a time series. Now we'll start looking at techniques, given what we know, that can be used to then forecast that time series. Let's start with this time series containing, trend seasonality, and noise and that's realistic enough for now. We could, for example, take the last value and assume that the next value will be the same one, and this is called naive forecasting. I've zoomed into a part of the data set here to show that in action. We can do that to get a baseline at the very least, and believe it or not, that baseline can be pretty good. But how do you measure performance? To measure the performance of our forecasting model,. We typically want to split the time series into a training period, a validation period and a test period. This is called fixed partitioning. If the time series has some seasonality, you generally want to ensure that each period contains a whole number of seasons. For example, one year, or two years, or three years, if the time series has a yearly seasonality. You generally don't want one year and a half, or else some months will be represented more than others. While this might appear a little different from the training validation test, that you might be familiar with from non-time series data sets. Where you just picked random values out of the corpus to make all three, you should see that the impact is effectively the same. Next you'll train your model on the training period, and you'll evaluate it on the validation period. Here's where you can experiment to find the right architecture for training. And work on it and your hyper parameters, until you get the desired performance, measured using the validation set. Often, once you've done that, you can retrain using both the training and validation data. And then test on the test period to see if your model will perform just as well. And if it does, then you could take the unusual step of retraining again, using also the test data. But why would you do that? Well, it's because the test data is the closest data you have to the current point in time. And as such it's often the strongest signal in determining future values. If your model is not trained using that data, too, then it may not be optimal. Due to this, it's actually quite common to forgo a test set all together. And just train, using a training period and a validation period, and the test set is in the future. We'll follow some of that methodology in this course. Fixed partitioning like this is very simple and very intuitive, but there's also another way. We start with a short training period, and we gradually increase it, say by one day at a time, or by one week at a time. At each iteration, we train the model on a training period. And we use it to forecast the following day, or the following week, in the validation period. And this is called roll-forward partitioning. You could see it as doing fixed partitioning a number of times, and then continually refining the model as such. For the purposes of learning time series prediction in this course, will learn the overall code for doing series prediction. Which you could then apply yourself to a roll-forward scenario, but our focus is going to be on fixed partitioning.
---------------------------------------------------------------
В предыдущих видео этой недели вы увидели всевозможные факторы, определяющие поведение временного ряда. Теперь мы рассмотрим методы, которые позволяют, с учётом наших знаний, предсказывать эти временные ряды. Начнём вот с такого временного ряда, содержащего тренд, сезонность и шум, на данном этапе он достаточно реалистичен. Можно, например, взять последнее значение и предположить, что следующее будет точно таким же — это называется наивным прогнозом. Я здесь увеличил часть графика, чтобы показать работу данного метода. Можно взять этот метод за отправную точку, и, хотите верьте, хотите — нет, но и этот прогноз может быть довольно хорош. Но как измерить его качество? Чтобы измерить качество модели предсказаний, нам, как правило, нужно разделить временной ряд на диапазоны: обучающий, валидационный и тестовый. Это называется фиксированным разделением. Если во временном ряде наблюдается сезонность, то обычно стоит убедиться, что в каждый из наборов попадёт целое число сезонов. Например, 1, 2 или 3 года, если у временного ряда годичная сезонность. Обычно не стоит брать 1.5 года — ведь тогда некоторые месяцы в выборке будут представлены более остальных. И хотя это может на первый взгляд отличаться от разбиения на обучающий, валидационный и тестовый наборы, который вам может быть знаком по работе с другими наборами данных, где данные просто берутся случайным образом из корпуса, образуя все три набора, — но вы увидите, что эффект будет, по сути, тот же самый. Дальше вы обучаете свою модель на данных из обучающего интервала и оцениваете её качество на валидационном интервале. Здесь можно экспериментировать в поиске подходящей для обучения архитектуры, и дорабатывать её, а также подстраивать гиперпараметры, пока вы не достигнете нужного качества, измеряемого по валидационной выборке. Обычно, добившись этого, вы обучаете модель заново на обоих наборах разом: обучающем и валидационном. А затем проверяете на тестовых данных, проверяя, что и на них работать будет не хуже. И если это так, то можно пойти на необычный шаг: снова обучить модель, используя вдобавок и тестовые данные. Почему можно так поступать? Потому, что тестовые данные — это данные, наиболее близкие к настоящему моменту [из имеющихся]. И потому они часто сильнее всего способны влиять на значения в будущем. Если модель обучена без использования, в т.ч., и этих данных — то она может оказаться неоптимальной. Из-за этого довольно часто от тестового набора данных отказываются вовсе, обучая с использованием лишь обучающего и валидационного интервалов, а тестовый набор "находится" в будущем. В этом курсе мы иногда будем придерживаться данной методологии. Подобное фиксированное разделение — очень простое и интуитивное, но есть и другой способ. Можно начать с короткого обучающего периода, постепенно увеличивая его, скажем, на один день за раз, или на неделю за раз. На каждой итерации мы обучаем модель на обучающем периоде и используем её, чтобы предсказать следующий день или неделю валидационного периода. Это разделение выборки с переносом. Можно расценивать его как серию фиксированных разбиений с постепенным уточнением модели. Поскольку цель курса — научиться предсказывать временные ряды, мы изучим общий код для предсказательных моделей, который вы сможете доработать для разделения с переносом, здесь же мы сосредоточимся на фиксированном разделении.

10(w1)-video7: Metrics for evaluating performance (18.MLg_4c)

Once we have a model and a period, then we can evaluate the model on it, and we'll need a metric to calculate their performance. So let's start simply by calculating the errors, which is the difference between the forecasted values from our model and the actual values over the evaluation period. The most common metric to evaluate the forecasting performance of a model is the mean squared error or mse where we square the errors and then calculate their mean. Well, why would we square it? Well, the reason for this is to get rid of negative values. So, for example, if our error was two above the value, then it will be two, but if it were two below the value, then it will be minus two. These errors could then effectively cancel each other out, which will be wrong because we have two errors and not none. But if we square the error of value before analyzing, then both of these errors would square to four, not canceling each other out and effectively being equal. And if we want the mean of our errors' calculation to be of the same scale as the original errors, then we just get its square root, giving us a root means squared error or rmse. Another common metric and one of my favorites is the mean absolute error or mae, and it's also called the mean absolute deviation or MAE. And in this case, instead of squaring to get rid of negatives, it just uses their absolute value. This does not penalize large errors as much as the mse does. Depending on your task, you may prefer the mae or the mse. For example, if large errors are potentially dangerous and they cost you much more than smaller errors, then you may prefer the mse. But if your gain or your loss is just proportional to the size of the error, then the mae may be better. Also, you can measure the mean absolute percentage error or mape, this is the mean ratio between the absolute error and the absolute value, this gives an idea of the size of the errors compared to the values. If we look at our data, we can measure the MAE using code like this. The keras metrics libraries include an MAE that can be called like this. With the synthetic data we showed earlier, we're getting about 5.93, let's consider that our baseline.
---------------------------------------------------------------
Располагая моделью и временным интервалом, можно оценить модель на этом интервале, для чего нам нужна какая-то мера качества. Сначала станем просто вычислять ошибки — разницу между значениями, предсказываемыми моделью, и реальными значениями за оцениваемый период. Чаще всего в качестве метрики качества предсказательных моделей берут среднеквадратичную ошибку (MSE), где отдельные ошибки возводятся в квадрат, а затем вычисляется их среднее. Но зачем возводить в квадрат? Для того, чтобы избавиться от отрицательных значений. Например, если мы ошиблись на 2, завысив значение, то ошибка будет 2. Но если предсказали на 2 меньше, ошибка будет -2. И такие ошибки будут взаимно сокращаться что неправильно: у нас две ошибки, а не их отсутствие. Но если мы возведём величину ошибки в квадрат, то обе этих ошибки будут равны 4, не сокращаясь друг с другом, а будучи равными. И если нужно, чтобы среднее от всех ошибок было того же масштаба, что и исходные значения ошибок, то нужно просто извлечь квадратный корень, что даёт нам корень из среднеквадратической ошибки, или RMSE. Ещё одна популярная метрика, одна из моих любимых — средняя абсолютная ошибка (MAE) также её называют средним абсолютным отклонением (MAD) Здесь, чтобы избавиться от отрицательных значений, вместо возведения в квадрат берутся абсолютные значения ошибок. Это не так сильно штрафует за большие ошибки, как MSE. В зависимости от задачи, вы можете предпочесть MAE или MSE. Например, если большие ошибки потенциально опасны и обходятся дороже, чем маленькие, тогда можно выбрать MSE. Но если ваша выгода или потеря пропорциональна размеру ошибки, то MAE может подойти лучше. Кроме того, можно измерять среднюю абсолютную ошибку в процентах, или MAPE. Это среднее отношение модуля ошибки к модулю значения. Оно даёт представление о размере ошибки в сравнении с прогнозируемыми величинами. Для наших данных можно измерить MAE, используя такой код. Библиотеки метрик Keras включают метрику MAE, которую можно вызвать так. На ранее показанных синтетических данных мы получаем около 5,93, Возьмём это значение за отправную точку.

11(w1)-video8: Moving average and differencing (18.MLg_4c)

A common and very simple forecasting method is to calculate a moving average. The idea here is that the yellow line is a plot of the average of the blue values over a fixed period called an averaging window, for example, 30 days. Now this nicely eliminates a lot of the noise and it gives us a curve roughly emulating the original series, but it does not anticipate trend or seasonality. Depending on the current time i.e. the period after which you want to forecast for the future, it can actually end up being worse than a naive forecast. In this case, for example, I got a mean absolute error of about 7.14. One method to avoid this is to remove the trend and seasonality from the time series with a technique called differencing. So instead of studying the time series itself, we study the difference between the value at time T and the value at an earlier period. Depending on the time of your data, that period might be a year, a day, a month or whatever. Let's look at a year earlier. So for this data, at time T minus 365, we'll get this difference time series which has no trend and no seasonality. We can then use a moving average to forecast this time series which gives us these forecasts. But these are just forecasts for the difference time series, not the original time series. To get the final forecasts for the original time series, we just need to add back the value at time T minus 365, and we'll get these forecasts. They look much better, don't they? If we measure the mean absolute error on the validation period, we get about 5.8. So it's slightly better than naive forecasting but not tremendously better. You may have noticed that our moving average removed a lot of noise but our final forecasts are still pretty noisy. Where does that noise come from? Well, that's coming from the past values that we added back into our forecasts. So we can improve these forecasts by also removing the past noise using a moving average on that. If we do that, we get much smoother forecasts. In fact, this gives us a mean squared error over the validation period of just about 4.5. Now that's much better than all of the previous methods. In fact, since the series is generated, we can compute that a perfect model will give a mean absolute error of about four due to the noise. Apparently, with this approach, we're not too far from the optimal. Keep this in mind before you rush into deep learning. Simple approaches sometimes can work just fine.
---------------------------------------------------------------
Популярный и очень простой метод прогнозирования состоит в вычислении скользящего среднего. Идея заключается в том, что что жёлтая линия отражает среднее значение значений голубой линии на фиксированном интервале — так называемом окне усреднения. Например, за 30 дней. Тем самым устраняется большая часть шума, выдавая кривую, грубо моделирующую исходный ряд, но здесь не учитываются ни тренды, ни сезонность. В зависимости от выбора момента времени, т.е. от периода, следом за которым должно идти предсказание будущего, результат может оказываться даже хуже, чем при наивном прогнозе. В этом случае, например, я получил среднюю абсолютную ошибку около 7.14. Один из способов этого избежать — убрать тренд и сезонность из временного ряда при помощи дифференцирования. Вместо изучения самого ряда, мы изучим разницу между значениями в момент T и в более ранний момент времени. В зависимости от временной шкалы, периодом [дифференцирования] может быть год, день, месяц или другое значение. Давайте возьмём интервал в год. Для этих данных с моментом времени T-365 мы получим разностный временной ряд, у которого нет тренда и нет сезонности. Тогда можно будет использовать скользящее среднее в предсказаниях для этого временного ряда, что даст нам вот такой прогноз. Но это прогноз лишь для разностного временного ряда, а не для исходного. Чтобы получить окончательный прогноз для исходного временного ряда, нужно прибавить обратно значение в момент T-365, и тогда мы получим такой прогноз. Выглядит намного лучше, не так ли? Если мы померим среднюю абсолютную ошибку на валидационном интервале, то получим около 5.8. Это немного лучше, чем наивный прогноз, но не сильно. Вы могли заметить, что наше скользящее среднее устранило много шума, но итоговый прогноз по-прежнему довольно шумный. Откуда этот шум взялся? Он пришёл из прошлых значений, которые мы добавили обратно к прогнозу. Так что можно этот прогноз улучшить, убрав также шум из прошлого, усреднив его скользящим окном. Если так сделать, получится намного более гладкий прогноз. И он даёт нам среднюю квадратичную ошибку на валидационном интервале всего порядка 4.5. И это гораздо лучше, чем у всех предыдущих методов. И поскольку ряд сгенерирован, можно подсчитать, что идеальная модель даст среднюю абсолютную ошибку около 4 — из-за шума. Очевидно, наш текущий подход не так уж далёк от оптимального. Имейте это в виду, прежде чем бросаться в глубокое обучение. Простые подходы иногда тоже отлично работают.

12(w1)-video9: Trailing versus centered windows (18.MLg_4c)

Note that we used the trailing window when computing the moving average of present values But we used a centered window to compute the moving average of past values. Moving averages using centered windows can be more accurate than using trailing windows. But we can't use centered windows to smooth present values since we don't know future values. However, to smooth past values we can afford to use centered windows. Okay, so now we've looked at a few statistical methods for predicting the next values in a time series. In the next video, you'll take a look at a screencast of this prediction in action. Once you've done the statistical forecasting, the next step of course will be to apply the machine-learning techniques you've been learning all along in TensorFlow and you'll do that next week.
---------------------------------------------------------------
Обратите внимание, что при вычислении скользящего среднего для текущего значения мы берём запаздывающее окно, от t-32 до t-1, Но при усреднении скользящим окном значений в прошлом мы используем центрированное окно от момента (t - 1) год, минус 5 дней — и до (t - 1) года плюс 5 дней. Скользящее среднее с центрированным окном может быть точнее, чем запаздывающее окно. Но мы не можем брать центрированное окно для сглаживания текущих значений, т.к. нам неизвестны будущие значения. Но чтобы сгладить прошлые значения, мы можем позволить себе использовать центрированное окно. Итак, мы сейчас рассмотрели некоторые статистические методы прогнозирования последующих значений во временном ряду. В следующем видео вы посмотрите рабочую демонстрацию такого прогнозирования. После статистического прогнозирования следующим этапом курса станет применение методов машинного обучения из TensorFlow, которые вы изучали. Этим вы и займётесь на следующей неделе.

13(w1)-video10: Forecasting (18.MLg_4c)

Let's take a look at running some statistical forecasting on the Synthetic Dataset that you've been working with. This should give us some form of baseline that we'll see if we can beat it with Machine Learning. You saw the details in the previous video and you'll go through this workbook in this video. The next code block condenses a lot of what you saw in the previous lessons. It will create a time series with trend, seasonality, and noise. You can see it in the graph here. Now to create a training validation set split, we'll simply split the array containing the data at index 1,000, and we will chart it. Again, we can see that the seasonality is maintained and it's still trending upwards. It also contains some noise. The validation set is similar and while the charts may appear different, checkout the x-axis. You can see that we've zoomed in quite a bit on it, but it is the same pattern. Now let's start doing some of the naive prediction. The first super simple prediction is to just predict the value at time period plus one. It's the same as the value of the current time period. So we'll create data called Naive Forecasting that simply copies the training data at time t minus 1. When we plot it, we see the original series in blue and the predicted one in orange. It's hard to make it out. So let's zoom in a little. We're looking at the start of the data, and that's sharp climb this C. So when we zoom in, we can see that the orange data is just one time-step after the blue data. This code will then print the mean squared and mean absolute errors. We'll see what they are. We get. 61.8 and 5.9 respectively. We'll call that our baseline. So now let's get a little smarter and try a moving average. In this case, the point in time t will be average of the 30 points prior to it. This gives us a nice smoothing effect. If we print out the error values for this, we'll get values higher than those for the naive prediction. Remember, for errors lower as better. So we can say that this is actually worse than the naive prediction that we made earlier on. So let's try a little trick to improve this. Since the seasonality on this Data is one year or 365 days, let's take a look at the difference between the data at time t and the data from 365 days before that. When we plot that, we can see that the seasonality is gone and we're looking at the raw data plus the noise. So now, if we calculate a moving average on this data, we'll see a relatively smooth moving average not impacted by seasonality. Then if we add back the past values to this moving average, we'll start to see a pretty good prediction. The orange line is quite close to the blue one. If we calculate the errors on this, you'll see that we have a better value than the baseline. We're definitely heading in the right direction. But all we did was just add in the raw historic values which are very noisy. What if, instead, we added in the moving average of the historic values, so we're effectively using two different moving averages? Now, our prediction curve is a lot less noisy and the predictions are looking pretty good. If we measure their overall error, the numbers agree with our visual inspection, the error rate has improved further. That was a pretty simple introduction to using some mathematical methods to analyze a series and get a basic prediction. With a bit of fiddling, we got a pretty decent one too. Next week, you'll look at using what you've learned from Machine Learning to see if you can improve on it.
---------------------------------------------------------------
Давайте посмотрим, как статистическое прогнозирование работает на наших синтетических данных. Мы возьмём его за отправную точку, и посмотрим, получится ли у нас превзойти её с помощью машинного обучения. Отдельные детали вы видели в прошлом видео, а в данном видео мы пройдёмся по всему блокноту. Перед началом убедитесь, что работаете в окружении Python 3 и с использованием GPU. Часть кода потребует наличия TensorFlow 2.0. Поэтому убедитесь, что он у вас есть. Этот код выведет его текущую версию. Если ваша версия меньше, чем 2.0, то нужно будет установить свежую версию. Чтобы установить её, используйте этот код. На момент записи этого курса, TensorfFlow 2.0 был на стадии первой бета-версии. Чтобы установить обновлённую, можно свериться с актуальной инструкцией на TensorFlow.org. Разобравшись с этим, вы увидите приглашение перезапустить окружение. Убедитесь, что вы это сделали. Проверьте, что у вас по-прежнему окружение с Python 3 и GPU, и запустите скрипт снова. Вы должны увидеть, что версия 2.0 теперь установлена. Следующий блок кода сводит воедино многое из того, что вы видели в предыдущем уроке. Здесь создаётся временной ряд с трендом, сезонностью и шумом. Вы можете увидеть его на этом графике. Чтобы теперь разделить данные на тренировочные и валидационные, просто разделим массив с данными по 1000-му элементу, и отобразим это на графике. И здесь тоже видно, что сезонность сохраняется, и тренд по-прежнему восходящий. А также присутствует шум. Валидационный набор похож, и хотя графики могут выглядеть по-разному, обратите внимание на ось абсцисс. Вы увидите, что масштаб [в валидации] несколько мельче, но паттерн тот же самый. Теперь давайте начнём с наивного прогноза. Первый очень простой прогноз — предсказывать значение на следующий временной период как равное значению в текущий период. Создадим массив под названием naive_forecasting, куда просто копируются тренировочные данные за момент времени t - 1. Когда мы построим график, то увидим исходный ряд голубого цвета и предсказанный оранжевого. Трудно их различить, так что давайте немного увеличим. Мы смотрим на начало ряда, и видим там резкий подъём. Увеличив график, мы видим, что оранжевая линия просто на шаг впереди голубой линии. Следующий код выводит среднеквадратичную и среднюю абсолютную ошибки. Посмотрим, каковы они. Мы получили 61,8 и 5,9 соответственно. Возьмём их за точку отсчёта. А теперь давайте будем немного умнее, и попробуем скользящее среднее. В этом случае значение в момент T будет средним из 30 предшествующих значений. Это даёт хороший эффект сглаживания. Если мы выведем значения ошибок для этого метода, то получим значения выше, чем при наивном прогнозе. Помните, что чем ниже ошибка, тем лучше. Поэтому можно сказать, что это на самом деле хуже наивного прогноза, выполненного ранее. Но давайте попробуем небольшой улучшающий трюк. Так как сезонность в этих данных — это один год, или 365 дней, то давайте посмотрим на разницу между данными в момент времени T и данными за 365 дней до этого. Когда мы выведем её на график, то увидим, что сезонность ушла, и мы видим плоские данные плюс шум. И если вычислять скользящее среднее на этих данных, то мы увидим относительно гладкое скользящее среднее, не подверженное сезонности. И если затем мы прибавить обратно прошлые значения к этому скользящему среднему, то мы увидим вполне неплохой прогноз. Оранжевая линия довольно близка к синей. Если мы посчитаем ошибки данного предсказания, то вы увидите, что их значения лучше, чем у базового варианта. Мы определенно движемся в верном направлении. Но мы здесь просто добавили сырые исторические данные — а в них полно шума. Что, если взамен добавить скользящее среднее по историческим данным, задействовав сразу два разных скользящих средних? Теперь наша прогнозируемая кривая куда менее шумная, и прогноз выглядит довольно хорошо. Если измерить общую ошибку, то цифры согласуются с нашей визуальной проверкой: уровень ошибки снова был улучшен. Это было довольно простое знакомство с тем, как использовать некоторые математические методы в анализе рядов и получать простейшие прогнозы. Немного повозившись, мы получили вполне приличный прогноз. На следующей неделе вы увидите, как использовать ваши знания машинного обучения, чтобы узнать, можно ли ещё улучшить этот результат.

14(w1)-Forecasting notebook (Lab 2): (18.MLg_4c)

Here is the link to the notebook that demonstrates statistical methods in forecasting.
C4_W1_Lab_2_forecasting.ipynb
Ungraded Lab: Statistical Forecasting on Synthetic Data
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W1/ungraded_labs/C4_W1_Lab_2_forecasting.ipynb#scrollTo=HrvQysecM9my
---------------------------------------------------------------

15(w1)- Week 1 Quiz: (18.MLg_4c)

1) What is an example of a Univariate time series?:
1 Baseball scores
2. Fashion items
3. Hour by hour temperature (+)
4. Hour by hour weather
2) What is an example of a Multivariate time series?:
1. Hour by hour weather (+)
2. Fashion items
3. Baseball scores
4. Hour by hour temperature
3) What is imputed data?:
1. Data that has been withheld for various reasons
2. A projection of unknown (usually past or missing) data (+)
3. A good prediction of future data
4. A bad prediction of future data
4) A sound wave is a good example of time series data:
1. False
2. True (+)
5) What is a Seasonality?:
1. Data that is only available at certain times of the year
2. Data aligning to the 4 seasons of the calendar
3. Weather data
4. A regular change in shape of the data (+)
6) What is trend?:
1. An overall consistent downward direction for data
2. An overall consistent flat direction for data
3. An overall direction for data regardless of direction (+)
4. An overall consistent upward direction for data
7) In the context of time series, what is noise?:
1. Sound waves forming a time series
2. Data that doesn't have a trend
3. Unpredictable changes in time series data (+)
4. Data that doesn't have seasonality
8) What is autocorrelation?:
1. Data that automatically lines up in trends
2. Data that automatically lines up seasonally
3. Data that doesn't have noise
4. Data that follows a predictable shape, even if the scale is different (+)
9)What is a non-stationary time series?:
1. One that has a disruptive event breaking trend and seasonality (+)
2. One that moves seasonally
3. One that has a constructive event forming trend and seasonality
4. One that is consistent across all seasons

16(w1)-Week 1 Wrap up: (18.MLg_4c)

This week you explored the nature of time-series data, and you saw some of its more common attributes such as seasonality and trend. You also looked at some statistical methods for predicting time series data.
Next week, you're going to start to look into using DNNs for time series classification, including the important task of understanding how to break up a time series into training and validation data.
---------------------------------------------------------------
На этой неделе вы изучили природу данных временных рядов и познакомились с некоторыми их наиболее распространенными атрибутами, такими как сезонность и тенденция. Вы также рассмотрели некоторые статистические методы прогнозирования данных временных рядов.
На следующей неделе вы начнете изучать использование DNN для классификации временных рядов, включая важную задачу понимания того, как разбить временной ряд на обучающие и проверочные данные.

17(w1)-Lecture Notes Week 1: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/ungradedLti/smWBG/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI
as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------

18(w1)-Assignment Troubleshooting Tips: (18.MLg_4c)

ere are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
1. Make sure to save your work before clicking the Submit button. If not, you might get an error message like in the code cell below. Remember that everything that you need to fill in within the graded functions is initialized to None.
2. Please do not rename the notebook. The grader will look for the original filename and its associated metadata so you should work on the file that is automatically opened when you click the Launch Notebook button. If you try to submit a renamed notebook, then you might also get an error like the one shown above.
3. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
4. After following the tips above and the grader still gives you 0/100, it's possible that the metadata needed for grading is corrupted. Please get a new lab notebook by refreshing your workspace (instructions here). Then copy your solutions into the new notebook. Make sure that all cells still run as expected then resubmit.
5. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by
following the instructions here. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
---------------------------------------------------------------

19(w1)-(Optional) Downloading your Notebook and Refreshing your Workspace: (18.MLg_4c)

This course uses Coursera Labs to provide a notebook environment and to grade your work. There might be some instances where you need to download your notebooks or refresh your workspace to start from scratch. This reading item outlines the steps to do so.
Downloading your Notebook
In case you need to download your notebook for troubleshooting or running in your local environment, you can follow these simple steps:
From the Menu Bar of the notebook you are working on, Click File → Save and Checkpoint to first save your progress.
Click File → Download as → Notebook (.ipynb). This should start downloading the file into your local machine.
---------------------------------------------------------------

19(w1)-Programming Assignment: Working with generated time seriese: (18.MLg_4c)

Week 1: Working with time series:
Welcome! In this assignment you will be working with time series data. All of the data is going to be generated and you will implement several functions to split the data, create forecasts and evaluate the quality of those forecasts.
Let's get started!

NEXT week_2 (18.MLg_4c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2)Deep Neural Networks for Time Series (18.MLg_4c)

(Глубокие нейронные сети для временных рядов)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 25 minutes
Self-study: 1h 36 min
Graded tasks (Tasks to be assessed): 2

(w2) Content (18.MLg_4c)

1. 2. 3. 4.

(w2) Introduction: (18.MLg_4c)

Having explored time series and some of the common attributes of time series such as trend and seasonality, and then having used statistical methods for projection, let's now begin to teach neural networks to recognize and predict on time series!
---------------------------------------------------------------
Изучив временные ряды и некоторые общие атрибуты временных рядов, такие как тенденция и сезонность, а затем применив статистические методы для прогнозирования, давайте теперь начнем учить нейронные сети распознавать и прогнозировать временные ряды!

1(w2)-video1: Introduction, A conversation with Andrew Ng (18.MLg_4c)

Welcome to the second week of this course. You learned about how to compute statistical analysis of a time series. In this week, you'll learn to apply a new network to these sequences. Yeah, we'll start with a relatively simple DNN, and if you remember DNNs all the way back like at the beginning of the specialization, so you're going to be able to bring those skills to bear on time-series data. So we're going to build a very simple DNN just like a three-layer DNN. Then one technique though that's I find really useful that you're going to learn this week, is being able to tune the learning rate of the optimizer. We'll all spent a lot of time hand-tuning learning rate. One of my most distinctive memories from couple of decades ago was a summer intern at Microsoft research staying up until 3:00 AM in the office, hand-tuning learning rates. I wish I could tune my own learning rate sometimes. So I think giving people a systematic way to do this, will be very useful. Yeah. I think so, and I know I've spent too many sleepless nights at it. So we tried to automate it here and so teach you a technique for automating it and hopefully it'll be useful, and hopefully it'll help you to start learning how to predict your time series data. By the end of this week, you have trained DNN on time series data that you saw last week and you get to see how well it does. Please go onto to the next video.
---------------------------------------------------------------
Добро пожаловать на вторую неделю этого курса. Вы узнали, как проводить статистический анализ временных рядов. На этой неделе вы научитесь применять к этим рядам нейросети. Да, мы начнём с довольно простой полносвязной нейросети (DNN), и если вы помните, DNN мы проходили давно, в самом начале специализации. И вы сможете перенести эти навыки на исследование временных рядов. Итак, мы собираемся построить очень простую DNN, всего лишь трёхслойную DNN. Затем применим один метод, который я нахожу очень полезным, и вы узнаете его на этой неделе: это возможность настраивать скорость обучения оптимизатора. Мы все потратили много времени, вручную подстраивая скорость обучения. Одно из моих наиболее ярких воспоминаний двадцатилетней давности — это когда я проходил летнюю стажировку в центре исследований Microsoft, просиживая в офисе до 3 утра и настраивая вручную скорость обучения. Хотелось бы мне подкрутить свою собственную скорость обучения. И я думаю, что если мы дадим людям системный подход к настройке, то это будет очень полезно. Да. Тоже так думаю, и знаю, что провёл за этим делом слишком много бессонных ночей. Итак, мы постарались автоматизировать настройку и научить вас методике её автоматизации, и я надеюсь, это будет полезно, и поможет вам начать изучение того, как предсказывать значения ваших временных рядов. К концу этой недели вы обучите DNN, используя временной ряд с прошлой недели, и посмотрите, насколько хорошо она с этим справится. Пожалуйста, переходите к следующему видео.

2(w2)-Preparing features and labels notebook (Lab 1): (18.MLg_4c)

In the next couple of videos, Laurence will demonstrate a series of commands to prepare features and labels. You can use the notebook here
to follow along and see links to the documentation of each command.
C4_W2_Lab_1_features_and_labels.ipynb
Ungraded Lab: Preparing Time Series Features and Labels
---------------------------------------------------------------

3(w2)-video2: Preparing features and labels (18.MLg_4c)

Last week you looked at creating a synthetic seasonal data set that contained trend, seasonality, and a bit of noise. You also looked at some statistical methods for analyzing the data set and making predictions from it. Some of the results you got were actually quite good, but there was no machine learning applied yet. This week, you're going to look at using some machine learning methods with the same data. Let's see where machine learning can take us. First of all, as with any other ML problem, we have to divide our data into features and labels. In this case our feature is effectively a number of values in the series, with our label being the next value. We'll call that number of values that will treat as our feature, the window size, where we're taking a window of the data and training an ML model to predict the next value. So for example, if we take our time series data, say, 30 days at a time, we'll use 30 values as the feature and the next value is the label. Then over time, we'll train a neural network to match the 30 features to the single label. So let's, for example, use the tf.data.Dataset class to create some data for us, we'll make a range of 10 values. When we print them we'll see a series of data from 0 to 9. So now let's make it a little bit more interesting. We'll use the dataset.window to expand our data set using windowing. Its parameters are the size of the window and how much we want to shift by each time. So if we set a window size of 5 with a shift of 1 when we print it we'll see something like this, 01234, which just stops there because it's five values, then we see 12345 etc, etc,. Once we get towards the end of the data set we'll have less values because they just don't exist. So we'll get 6789, and then 789, etc, etc,. So let's edit our window a little bit, so that we have regularly sized data. We can do that with an additional parameter on the window called drop_remainder. And if we set this to true, it will truncate the data by dropping all of the remainders. Namely, this means it will only give us windows of five items. So when we print it, it will now look like this, starting at 01234 and ending at 56789. Great, now let's put these into numpy lists so that we can start using them with machine learning. Good news is, is that this is super easy, we just call the .numpy method on each item in the data set, and when we print we now see that we have a numpy list. Okay, next up is to split the data into features and labels. For each item in the list it kind of makes sense to have all of the values but the last one to be the feature, and then the last one can be the label. And this can be achieved with mapping, like this, where we split into everything but the last one with :-1, and then just the last one itself with -1. Which gives us this output when we print, which now looks like a nice set of features and labels. Typically, you would shuffle their data before training. And this is possible using the shuffle method. We call it with the buffer size of ten, And when we print the results, we'll see our features and label sets have been shuffled. Finally, we can look at batching the data, and this is done with the batch method. It'll take a size parameter, and in this case it's 2. So what we'll do is we'll batch the data into sets of two, and if we print them out, we'll see this. We now have three batches of two data items each. And if you look at the first set, you'll see the corresponding x and y. So when x is four, five, six and seven, our y is eight, or when x is zero, one, two, three, you'll see our y is four. Okay, now that you've seen the tools that let us create a series of x and y's, or features and labels, you have everything you need to work on a data set in order to get predictions from it. We'll take a look at a screen cast of this code next, before moving on to creating our first neural networks to run predictions on this data.
---------------------------------------------------------------
На прошлой неделе вы посмотрели, как создать синтетический набор данных с сезонностью, в котором есть тренд, сезонность и немного шума. Вы также рассмотрели некоторые статистические методы анализа таких данных и их прогнозирования. Некоторые из полученных результатов были уже весьма неплохи, но дело ещё не дошло до применения машинного обучения. На этой неделе вы рассмотрите, как на тех же данных использовать некоторые методы машинного обучения. Давайте посмотрим, к чему машинное обучение может нас привести. Прежде всего, как и в любой другой задаче машинного обучения, нам нужно разбить данные на признаки и метки. В данном случае признаками будет некоторое число значений ряда, а меткой — следующее за ними значение. Назовём количество значений, которые будем считать признаками, — размером окна, т.к. мы берём окно с данными, и обучаем модель предсказывать следующее значение. Например, если брать из нашего ряда, данные, например, за 30 дней сразу, то 30 значений мы возьмём в качестве признаков, а следующее за ними — в качестве метки. А затем мы научим нейронную сеть находить соответствие между 30 признаками и единственной меткой. Давайте, возьмём, например, класс tf.data.Dataset, чтобы создать некоторые данные. Возьмём диапазон из 10 значений. Когда мы напечатаем их, мы увидим ряд чисел от 0 до 9. А теперь сделаем немного поинтереснее. Мы используем dataset.window, чтобы расширить наш набор данных с помощью окон. Его параметры — это размер окна и шаг, на который мы хотим каждый раз сдвигать окно. Если взять размер окна как 5, и шаг в 1, и вывести результат на экран, то мы увидим что-то подобное: 0, 1, 2, 3, 4 — на этом вывод прекратится, т.к. в окно попадает лишь 5 значений. Далее мы увидим 1, 2, 3, 4, 5, и т. д., и т. п. Ближе к концу набора данных значений становится меньше, т.к. дальше их просто не существует. Так что мы получим 6, 7, 8, 9, потом 7, 8, 9, и т.д. Немного подправим наше окно, чтобы данные были одного размера. Это можно сделать при помощи дополнительного параметра метода window под названием drop_remainder. Если задать его равным True, метод обрежет данные, отбросив все остатки. А именно, это означает, что он вернёт нам только окна из пяти элементов. И когда мы распечатаем новый вариант, он будет выглядеть так, начинаясь с 0, 1, 2, 3, 4 и заканчиваясь на 5, 6, 7, 8, 9. Отлично, а теперь давайте поместим их в списки numpy, чтобы можно было использовать их для машинного обучения. Хорошая новость в том, что это очень просто: мы лишь вызываем метод .numpy для каждого элемента в наборе данных, и когда мы их выводим, то видим, что это списки numpy. Так, теперь нужно разделить данные на признаки и метки. Для каждого элемента в списке имеет смысл сделать все значения, кроме последнего, — признаками, а последний — меткой. А это можно получить отображением, как здесь, где мы разделили все списки на две части: всё, кроме последнего, при помощи [:-1], и сам последний — [-1:] При выводе мы получаем такой результат, теперь это похоже на хороший набор признаков и меток. Как правило, данные перед обучением перемешивают. Это можно сделать, используя метод shuffle. Мы вызываем его с размером буфера, равным 10, т.к. именно столько элементов содержится в наших данных. И когда мы выводим результат, то видим, что наши наборы признаков и меток были перемешаны. Наконец, посмотрим, как объединить данные в пакеты — это делается методом batch. Он принимает размер пакета как параметр — в данном случае, 2. Тем самым, мы делим данные на пакеты по два элемента, и если их вывести на экран, то увидим вот что. Теперь у нас есть три пакета, по два элемента данных в каждом. Если посмотреть на первый набор, то вы увидите там соответствующие х и у. Так, когда x = [4, 5, 6, 7], то y = [8], а когда x = [0, 1, 2, 3], то вы увидите, что y = [4]. Теперь, когда вы увидели инструменты, позволяющие создавать наборы х и у, т.е., признаков и меток, — у вас есть всё необходимое для подготовки данных к получению предсказаний. Этот же самый код мы рассмотрим поэтапно, прежде чем перейти к созданию нашей первой нейросети и получению прогнозов на этих данных.

4(w2)-video3: Preparing features and labels (screencast) (18.MLg_4c)

In the previous video, you saw how to prepare a time series for machine learning by windowing the data. You saw the code to create a very simple dataset, and then you learned how you can prepare that dataset as features and labels or x's and y's. In this video, you'll go through a screencast of a notebook that contains all of that code. First, we'll create a simple dataset, and it's just a simple range containing 10 elements from zero to nine. We'll print each one out on its own line as you can see. Next, we'll window the data into chunks of five items, shifting by one each time. We'll see that this gives us the output of the first five items, and then the second five items, and then the third five items, etc. At the end of the dataset, when there isn't enough data to give us five items, you'll see shorter lines. To just get chunks of five records, we'll set drop_reminder to true. When we run it, we'll see that our data looks like this. We've got even sets that are the same size. TensorFlow likes its data to be in numpy format. So we can convert it easily by calling the dot numpy method and when we print it, we can see it's now listed in square brackets. Next up is to split into x's and y's or features and labels. We'll take the last column as the label, and we'll split using a lambda. We'll split the data into `:-1`, which is all of the columns except the last one, and `-1` which is the last one only. Now we can see that we have a set of four items and a single item. Remember that the `-1` denotes the last value in the list, and `:-1` denotes everything about the last value. As such, we can see zero, one, two, three and one, two, three, four before the split just for example. Next of course, is to shuffle the data. This is achieved with the shuffle method. This helps us to rearrange the data so as not to accidentally introduce a sequence bias. Multiple runs will show the data in different arrangements because it gets shuffled randomly. Finally, comes batching. By setting a batch size of two, our data gets batched into two x's and two y's at a time. For example, as we saw earlier, if x is zero, one, two, three, we can see that the corresponding y is four or if x is five, six, seven, eight, then our y is nine. So that's the workbook with the code that splits a data series into windows. Try it out for yourself, and once you're familiar with what it does, proceed to the next video. There you'll move to the seasonal dataset that you've been using two dates, and with this windowing technique, you'll see how to set up x's and y's that can be fed into a neural network to see how it performs with predicting values.
---------------------------------------------------------------
В предыдущем видео вы увидели, как подготовить временные ряды к машинному обучению, выбирая данные окном. Вы видели код для создания очень простого набора данных и узнали, как разделить этот набор данных на признаки и метки, т.е., X и Y. В этом видео мы пройдёмся разберём всё содержимое блокнота с кодом. Для начала нужно, чтобы у вас был установлен TensorFlow 2.0. Чтобы проверить вашу версию, запустите этот блок кода. Он должен вывести 2.0.0-что-то ещё. В данном случае, я использую ночную сборку, отсюда -dev<код> на конце. Если вам нужна версия 2.0, её можно установить с помощью следующего кода. Tf-nightly-2.0-preview — версия для разработчиков, которую я только что упомянул, либо можно установить TF 2.0 с помощью pip install tenorflow, как здесь. Версия может отличаться от b1, т.к. к моменту записи этого видео для TensorFlow была выпущена бета 1. Сверьтесь со свежими инструкциями на tenorflow.org для установки продуктовой сборки. После того, как вы установили TensorFlow, можно запустить этот код. Сначала мы создадим простой набор данных, и это просто диапазон, содержащий 10 элементов от нуля до девяти. Как видите, мы вывели каждый из них на отдельной строке. Дальше мы разобьём набор данных на окна по 5 элементов, каждый раз делая сдвиг на один элемент. Мы видим, что это даёт нам на выходе сначала первые 5 элементов, потом вторые 5 элементов, затем третьи 5 элементов, и т. д. В конце набора данных, когда данных на 5 элементов не хватает, видно более короткие строки. Чтобы остались лишь блоки из пяти записей, мы установим для drop_reminder значение true. Запустив код, мы увидим, что наши данные выглядят так. Мы получили ровные наборы одинакового размера. TensorFlow любит, чтобы данные были в формате numpy. И мы можем легко их преобразовать, вызвав метод .numpy, и если вывести его результат, то мы видим, что теперь списки идут в квадратных скобках. Далее следует разделить данные на X и Y — признаки и метки. Мы возьмем последний столбец в качестве метки, и разделим списки, используя лямбда-функцию. Мы разделим данные с помощью [:-1], что даёт все столбцы, кроме последнего, и [-1:], что даёт только последний столбец. Теперь мы видим, что у нас есть наборы по четыре элемента и по одному элементу. Помните, что [-1:] обозначает последнее значение в списке, а [:-1] означает всё, кроме последнего значения. Таким образом, мы видим, например, 0, 1, 2, 3 и 1, 2, 3, 4 — до точки разделения. Дальше, конечно, нужно перемешать данные. И это можно сделать, используя метод shuffle. Он помогает нам переупорядочить данные так, чтобы модель случайно не стала зависеть от порядка в данных. Если запускать этот блок многократно, данные всякий раз будут идти в другом порядке, т.к. этот порядок случайный. И наконец, подготовка пакетов. Установив размер пакета 2, мы группируем данные по два X и два Y за раз. Например, как мы уже видели, если x = [0, 1, 2, 3], то мы видим, что соответствующий y = 4, а если x = [5, 6, 7, 8], тогда y = 9. Итак, это рабочий блокнот с кодом, который разбивает временной ряд на окна. Попробуйте его самостоятельно, и когда вы освоитесь в этом коде, переходите к следующему видео. Там вы перейдёте к сезонному набору данных, который уже использовали раньше, и пользуясь данным методом разбиения на окна, вы посмотрите, как задать X и Y так, чтобы можно было подать их на вход нейросети и посмотреть, как она справится с прогнозированием значений.

5(w2)-Single layer neural network notebook (Lab 2): (18.MLg_4c)

The next lectures will show how you can feed windowed datasets to a single neural network. You can use the notebook here to follow along or you can run it after the screencast.
C4_W2_Lab_2_single_layer_NN.ipynb
Ungraded Lab: Training a Single Layer Neural Network with Time Series Data
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W2/ungraded_labs/C4_W2_Lab_2_single_layer_NN.ipynb
---------------------------------------------------------------

6(w2)-video4: Feeding windowed dataset into neural network (18.MLg_4c)

In the last videos you saw how to prepare time series data for machine learning by creating a window dataset where the previous n values could be seen as the input features are x. And the current value with any time stamp is the output label or the y. It would then look a little bit like this. With a number of input values on x, typically called a window on the data. You saw in the previous videos how to use the tools in tensor flow datasets to create these windows. This week you'll adapt that code to feed a neural network and then train it on the data. So let's start with this function that will call a windows dataset. It will take in a data series along with the parameters for the size of the window that we want. The size of the batches to use when training, and the size of the shuffle buffer, which determines how the data will be shuffled. The first step will be to create a dataset from the series using a tf.data dataset. And we'll pass the series to it using its from_tensor_slices method. We will then use the window method of the dataset based on our window_size to slice the data up into the appropriate windows. Each one being shifted by one time set. We'll keep them all the same size by setting drop remainder to true. We then flatten the data out to make it easier to work with. And it will be flattened into chunks in the size of our window_size + 1. Once it's flattened, it's easy to shuffle it. You call a shuffle and you pass it the shuffle buffer. Using a shuffle buffer speeds things up a bit. So for example, if you have 100,000 items in your dataset, but you set the buffer to a thousand. It will just fill the buffer with the first thousand elements, pick one of them at random. And then it will replace that with the 1,000 and first element before randomly picking again, and so on. This way with super large datasets, the random element choosing can choose from a smaller number which effectively speeds things up. The shuffled dataset is then split into the xs, which is all of the elements except the last, and the y which is the last element. It's then batched into the selected batch size and returned.
---------------------------------------------------------------
В прошлых видео вы посмотрели, как подготовить данные временных рядов для машинного обучения, создав набор данных на основе окон, где предыдущие n значений можно взять в качестве входных признаков — X, а текущее значение в любой момент времени служит выходной меткой, или Y. Это выглядит примерно так, где количество входных значений в X называется окном данных. Вы видели в предыдущих видео, как использовать инструменты tensorflow.datasets для создания таких окон. На этой неделе вы адаптируете этот код для ввода данных в нейросеть и обучения её на этих данных. Итак, давайте начнём с этой функции, которую мы назовём windowed_dataset. Она принимает на вход временной ряд, а также параметры: нужный нам размер окна, размер пакета для обучения, а также размер буфер для перемешивания, определяющий, как данные будут перемешаны. Первым шагом будет создание набора данных на основе ряда с использованием tf.data.Dataset. Мы передадим в него ряд, используя метод from_tensor_slices. Затем мы используем метод dataset.window, основываясь на window_size, чтобы нарезать данные на соответствующие окна, каждое из которых сдвинуто на один шаг по времени. Мы создадим их все одного размера, задав drop_remainder=True. Затем мы сделаем данные плоскими, чтобы с ними было проще работать. И они будут собраны в группы размером с наше window_size + 1. Когда они стали плоскими, их легко перемешать. Вы вызываете метод shuffle, передавая параметр shuffle_buffer. Использование этого параметра немного ускоряет работу. Так, например, если у вас в наборе 100 000 элементов, а вы установите буфер, равный 1000, то просто заполнит буфер первой тысячей элементов, возьмёт один из них наугад, затем заменит его 1001-м элементом, случайно выберет ещё один, и так далее. Тем самым, для очень больших наборов данных можно выбирать элемент случайно из меньшего числа, что существенно ускоряет дело. Перемешанный набор данных затем разделяется на X, т.е., все элементы, кроме последнего, — и Y, которым будет последний элемент. Затем данные раскладываются по пакетам заданного размера и возвращаются.

7(w2)-video5: Single layer neural network (18.MLg_4c)

Now that we have a window datasets, we can start training neural networks with it. Let's start with a super simple one that's effectively a linear regression. We'll measure its accuracy, and then we'll work from there to improve that. Before we can do a training, we have to split our dataset into training and validation sets. Here's the code to do that at time step 1000. We can see that the training data is the subset of the series called x train up to the split time. Here's the code to do a simple linear regression. Let's look at it line by line. We'll start by setting up all the constants that we want to pass to the window dataset function. These include the window size on the data, the batch size that we want for training, and the size of the shuffled buffer as we've just discussed. Then we'll create our dataset. We'll do this by taking our series, and in the notebook that you'll go through later, you'll create the same synthetic series as you did in week one. You'll pass it your series along what your desired window size, batch size, and shuffled buffer size, and it will give you back a formatted datasets that you could use for training. I'm then going to create a single dense layer with its input shape being the window size. For linear regression, that's all you need. I'm using this approach. By passing the layer to a variable called L0, because later I'm want to print out its learned weights, and it's a lot easier for me to do that if I have a variable to refer to the layer for that. Then I simply define my model as a sequential containing the sole layer just like this. Now I'll compile and fit my model with this code. I'll use the mean squared error loss function by setting loss to MSE, and my optimizer will use Stochastic Gradient Descent. I'd use this methodology instead of the raw string, so I can set parameters on it to initialize it such as the learning rate and the momentum. Experiment with different values here to see if you can get your model to converge more quickly or more accurately. Next you can fit your model by just passing it the dataset, which has already been preformatted with the x and y values. I'm going to run for a 100 epochs here. Ignoring the epoch but epoch output by setting verbose to zero. Once it's done training, you can actually inspect the different weights with this code. Remember earlier when we referred to the layer with a variable called L 0? Well, here's where that's useful. The output will look like this. If you inspect it closely, you will see that the first array has 20 values in it, and the secondary has only one value. This is because the network has learned a linear regression to fit the values as best as they can. So each of the values in the first array can be seen as the weights for the 20 values in x, and the value for the second array is the b value.
---------------------------------------------------------------
Теперь, когда у нас есть оконный набор данных, можно приступить к обучению нейросети. Давайте начнем со сверхпростой сети, — фактически, с линейной регрессии. Мы измерим её точность, а затем поработаем над её улучшением. Перед обучением нам нужно разделить набор данных на обучающую и валидационную выборки. Вот код, выполняющий такое разбиение относительно момента времени 1000. Мы видим, что обучающая выборка — это подмножество ряда до момента времени split_time, и называется x_train. Вот код для модели простой линейной регрессии. Давайте разберём его построчно. Мы начинаем с определения всех констант, которые хотим передать в функцию windowed_dataset. Сюда входят размер окна данных, размер пакета, при котором мы хотим обучать сеть, и размер буфера перемешивания, который мы только что обсуждали. Затем мы создаём наши выборки. Мы сделаем это, взяв наш ряд, а в блокноте, который вы увидите позже, вы создадите тот же синтетический ряд, который уже создавали на первой неделе. Нужно передать этот ряд, а также размер окна, размер пакета и размер буфера перемешивания, — и функция вернёт вам отформатированный набор данных, который можно использовать для обучения. Далее я создаю один полносвязный слой со входом, равным размеру окна. Для линейной регрессии нам больше ничего не требуется. Я делаю это вот так, передавая слой в переменную с именем l0, т.к. я хочу позже вывести веса, которые слой выучил, а это будет намного легче сделать, если у меня будет переменная, на которую можно ссылаться для обращения к слою. Далее я просто определяю модель как последовательную и содержащую единственный слой, вот таким образом. Теперь я компилирую модель и запускаю её обучение. Я использую среднеквадратичную ошибку в качестве функции потерь, установив параметр loss = "mse", а мой оптимизатор будет использовать стохастический градиентный спуск (SGD). Я использую этот способ [выбора оптимизатора] вместо строкового параметра, чтобы можно было задать ему параметры инициализации, такие как скорость обучения lr и импульс momentum. Поэкспериментируйте с различными значениями этих параметров, чтобы посмотреть, удастся ли вам заставить вашу модель сходиться быстрее или точнее. Дальше вы запускаете обучение модели, просто передав ей набор данных, который уже отформатирован и содержит значения X и Y. Я собираюсь обучать модель в течение 100 эпох и ничего не выводить между эпохами, установив для этого verbose=0. Как только обучение закончилось, вы можете изучить веса сети с помощью данного кода. Помните, мы ранее сохранили ссылку на слой в переменную с именем l0? Именно здесь она и пригодилась. Результат будет выглядеть примерно так. Если вы внимательно его изучите, то увидите, что в первом массиве содержится 20 значений, а во втором — только одно. Это потому что сеть обучила веса линейной регрессии, чтобы как можно лучше отвечать заданным значениям. Таким образом, значения из первого массива будут весами для 20 значений вектора x, а значение во втором массиве — это b.

8(w2)-video6: Machine learning on time windows (18.MLg_4c)

So if you think back to this diagram and you consider the input window to be 20 values wide, then let's call them x0, x1, x2, etc, all the way up to x19. But let's be clear. That's not the value on the horizontal axis which is commonly called the x-axis, it's the value of the time series at that point on the horizontal axis. So the value at time t0, which is 20 steps before the current value is called x0, and t1 is called x1, etc. Similarly, for the output, which we would then consider to be the value at the current time to be the y.
---------------------------------------------------------------
Если вернуться к этой диаграмме, и взять входное окно шириной в 20 значений — давайте назовём их x0, x1, x2, ..., x19. Но давайте проясним. xi — это не значение на горизонтальной оси, которую обычно называют осью х, — это значение временного ряда в этой точке на горизонтальной оси. То есть, значение в момент времени t0, за 20 шагов до текущего значения, — называется x0, значение в t1 — это x1, и т.д. А выходное значение, которое мы считаем значением на текущий момент времени, — мы обозначаем за y.

9(w2)-video7: Prediction (18.MLg_4c)

So now, if we look at the values again and see that these are the weights for the values at that particular timestamp and b is the bias, we can do a standard linear regression like this to predict the value of y at any step by multiplying out the x values by the weights and then adding the bias. So for example, if I take 20 items in my series and print them out, I can see the 20x values. If I want to predict them, I can pass that series into my model to get a prediction. The NumPy new axis then just reshapes it to the input dimension that's used by the model. The output will look like this. The top array is the 20 values that provide the input to our model and the bottom is the predicted value back from the model. So we've trained our model to say that when it sees 20 values like this, the predicted next value is 49.08478. So if we want to plot our forecasts for every point on the time-series relative to the 20 points before it where our window size was 20, we can write code like this. We create an empty list of forecasts and then iterate over the series taking slices and window size, predicting them, and adding the results to the forecast list. We had split our time series into training and testing sense taking everything before a certain time is training and the rest is validation. So we'll just take the forecasts after the split time and load them into a NuimPy array for charting. That chart looks like this with the actual values in blue and the predicted ones in orange. You can see that our predictions look pretty good and getting them was relatively simple in comparison with all the statistical gymnastics that we had to do in the last videos. So let's measure the mean absolute error as we've done before, and we can see that we're in a similar ballpark to where we were with a complex analysis that we did previously. Now that's just using a single layer in a neural network to calculate a linear regression. Let's see if we could do better with a fully-connected DNN next. Before you get to that, we'll go through the workbook for this lesson to ensure that you understand everything we've done up to now. The next video will be a screencast of going through that and then you'll work on the DNN after that.
---------------------------------------------------------------
Так что теперь, если снова посмотреть на значения, и увидеть, что это веса для значений в конкретный момент времени, а b — общее смещение, то можно построить стандартную линейную регрессию, вроде этой, чтобы предсказывать значение у на любой момент времени, перемножая значения х с этими весами, а затем добавляя смещение. Так, если я возьму для примера 20 элементов из моего ряда, и выведу их на экран, то увижу 20 значений из x. Чтобы их предсказать, можно передать этот ряд в мою модель, получая прогноз. np.newaxis просто изменяет форму массива так, чтобы его размерность соответствовала входу модели. Результат будет выглядеть вот так. Верхний массив — это 20 значений которые обеспечивают вход для нашей модели, а нижний — предсказанное значение, которое вернула модель. Итак, мы обучили нашу модель при виде 20 подобных значений давать прогноз, что следующее значение составляет 49,08478. И если нам нужно построить прогноз для каждой точки временного ряда, основываясь на 20 предшествующих значениях, где 20 — это наш размер окна, — то для этого можно написать подобный код. Создаем пустой список для прогнозов, а затем проходим в цикле по ряду, вырезая данные под размер окна, прогнозируя для них результат и добавляя его к списку прогнозов. Мы разделили наш временной ряд на обучающую и тестовую выборки, взяв все значения до определённого момента в качестве обучающей выборки, а остальное — валидационной. Итак, возьмём прогнозы после точки разделения и загрузим их в массив numpy для построения графика. Этот график выглядит вот так, здесь реальные данные — голубого цвета, а предсказанные — оранжевого. Видно, что наши прогнозы выглядят довольно хорошо, и получать их было относительно просто, по сравнению со всеми теми статистическими упражнениями, которые мы делали в предыдущих видео. Давайте измерим среднюю абсолютную ошибку, как мы уже делали раньше, и увидим, что мы примерно в одной весовой категории с тем сложным анализом, который мы делали раньше. Это мы использовали лишь один слой нейросети для вычисления линейной регрессии. Давайте далее посмотрим, можно ли добиться большего с полносвязной DNN. Прежде чем переходить к ней, пройдёмся по блокноту для нынешнего урока, чтобы убедиться, что вы поняли всё, что мы уже успели проделать. В следующем видео вы увидите, как это происходит, а затем уже начнёте работать над DNN.

10(w2)-video8: More on single layer neural network (18.MLg_4c)

In the last video, you saw how to write code to get a machine learned linear regression model of the time-series data. In this video, I'll step you through the notebook with all the code and then you can try it out for yourself. Next we'll run the code for all the helper functions that set up a data series as well as creating the data series itself. At the bottom of this code section, you'll see the code for setting up the series, splitting it into training and validation, and then setting up the constants to use for window size, batch size and all that. Now you can create the helper function for the window dataset as we saw in the previous video. Now we'll create our model by first getting a window dataset from the training data which as you may remember, was split off from the main set. We'll then define the model, compile it, and fit it to the data that we have, when it's done it will print out the layer weights. You can see the layer weights which provide the coefficients for the x values and the linear regression, as well as the bias value for their regression here. We got this by calling the get weights method on the layer. We can now plot the predictions for each of the elements in the validation split of the series, the predictions or an orange and the actual values are in blue. Finally, we can measure the mean absolute error between the valid data and the predicted results. Do note that you might see different values here, and in particular as you swap between notebooks, they might change drastically. Remember that the series has a random elements in it with the noise and as such measuring error in one notebook against another may not be the most accurate way because the noise will change. So don't worry if sometimes you see slightly larger values if you were expecting smaller ones. Next we'll take a look at using a deep neural network to predict on this data.
---------------------------------------------------------------
В предыдущем видео вы видели, как написать код обучения модели линейной регрессии для временного ряда. В этом видео мы пройдёмся пошагово по блокноту со всем этим кодом, а затем вы сможете попробовать всё сами. Как и раньше, проверьте, что у вас есть TensorFlow 2.0 для работы с этим кодом. Если у вас его нет, вы можете установить ночную версию или последовать инструкциям на TensorFlow.org для установки современной версии. Далее мы запустим код, содержащий вспомогательные функции, которые обрабатывают или даже создают временные ряды. В нижней части этого блока кода вы найдёте код для организации рядов: разбиения данных на обучающую и валидационную выборки, а затем задаются значения констант для размера окна, размера пакета и прочего. Теперь можно создать вспомогательную функцию для построения оконного набора данных, который мы видели в предыдущем видео. Теперь создадим нашу модель — сначала получим оконный набор данных из обучающих данных, которые, как вы, наверное, помните, были отрезаны от общего набора данных. Затем мы определим модель, скомпилируем её и запустим обучение на имеющихся данных. Когда оно завершится, то выведет веса слоя. Вы видите веса слоя, предоставляющие коэффициенты для значений х в линейной регрессии, а также значение смещения для этой регрессии. Мы получили их, вызвав у слоя метод get_weights. Теперь мы можем вывести на график прогнозы для каждого из элементов валидационной выборки: предсказания — оранжевые, а реальные значения — голубые. Наконец, мы можем измерить среднюю абсолютную ошибку между реальными значениями и предсказанными результатами. Обратите внимание, что у вас это значение может варьироваться, в частности, оно может сильно меняться при переключении между блокнотами. Помните, что ряд несёт элемент случайности в виде шума, и измерение ошибки в одном блокноте и сравнение её с другим может не слишком совпадать, потому что шум будет отличаться. Так что не волнуйтесь, если иногда заметите несколько более высокие значения, хотя ожидали меньших. Далее мы рассмотрим, как для предсказания этих данных использовать глубокую нейронную сеть.

11(w2)-Deep neural network notebook (Lab 3): (18.MLg_4c)

The last section for this week will demonstrate using multi-layer neural networks and you can use the notebook here as reference for the upcoming videos.
Ungraded Lab: Training a Deep Neural Network with Time Series Data
C4_W2_Lab_3_deep_NN.ipynb
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W2/ungraded_labs/C4_W2_Lab_3_deep_NN.ipynb#scrollTo=dxFGlX1S53mg
---------------------------------------------------------------

12(w2)-video9: Deep neural network training, tuning and prediction (18.MLg_4c)

Okay, so this week you've been looking at machine learning for predicting the next value in a sequence. You've learned how to break your data down into window chunks that you could train on, and then you saw a simple single layer neural network that gave you what was effectively a linear regression. Now let's take that to the next step with a DNN to see if we can improve our model accuracy. It's not that much different from the linear regression model we saw earlier. And this is a relatively simple deep neural network that has three layers. So let's unpack it line by line. First we'll have to get a data set which will generate by passing in x_train data, along with the desired window size, batch size, and shuffle buffer size. We'll then define the model. Let's keep it simple with three layers of 10, 10, and 1 neurons. The input shape is the size of the window and we'll activate each layer using a relu. We'll then compile the model as before with a mean squared error loss function and stochastic gradient descent optimizer. Finally, we'll fit the model over 100 epochs, and after a few seconds of training, we'll see results that look like this. It's pretty good still. And when we calculate the mean absolute error, we're lower than we were earlier, so it's a step in the right direction. But it's also a somewhat a stab in the dark, particularly with the optimizer function. Wouldn't it be nice if we could pick the optimal learning rate instead of the one that we chose? We might learn more efficiently and build a better model. Now let's look at a technique for that that uses callbacks that you used way back in the first course. So here's a code for the previous neural network. But I've added a callback to tweak the learning rate using a learning rate scheduler. You can see that code here. This will be called at the callback at the end of each epoch. What it will do is change the learning rates to a value based on the epoch number. So in epoch 1, it is 1 times 10 to the -8 times 10 to the power of 1 over 20. And by the time we reach the 100 epoch, it'll be 1 times 10 to the -8 times 10 to the power of 5, and that's 100 over 20. This will happen on each callback because we set it in the callbacks parameter of model.fit(). After training with this, we can then plot the last per epoch against the learning rate per epoch by using this code, and we'll see a chart like this. The y-axis shows us the loss for that epoch and the x-axis shows us the learning rate. We can then try to pick the lowest point of the curve where it's still relatively stable like this, and that's right around 7 times 10 to the -6. So let's set that to be our learning rate and then we'll retrain. So here's the same neural network code, and we've updated the learning rate, so we'll also train it for a bit longer. Let's check the results after training for 500 epochs. Here's the codes to plot out the loss that was calculated during the training, and it will give us a chart like this. Which upon first inspection looks like we're probably wasting our time training beyond maybe only 10 epochs, but it's somewhat skewed by the fact that the earlier losses were so high. If we cropped them off and plot the loss for epochs after number 10 with code like this, then the chart will tell us a different story. We can see that the loss was continuing to decrease even after 500 epochs. And that shows that our network is learning very well indeed. And the results of the predictions overlaid against the originals looks like this. And the mean absolute error across the results is significantly lower than earlier. I'll take you through a screencast of this code in action in the next video. Using a very simple DNN, we've improved our results very nicely. But it's still just a DNN, there's no sequencing taken into account, and in a time series like this, the values that are immediately before a value are more likely to impact it than those further in the past. And that's the perfect set up to use RNNs like we had in the natural language course. Now we'll look at that next week, but first, let's dig into this code.
---------------------------------------------------------------
На этой неделе вы посмотрели, как применять машинное обучение для прогнозирования следующих значений в последовательности. Вы узнали, как разбить ваши данные на окна для обучения на них, а затем увидели простую однослойную нейронную сеть, которая фактически решала задачу линейной регрессии. Теперь давайте пойдём дальше: возьмём DNN и посмотрим, удастся ли нам при этом улучшить точность нашей модели. Здесь мало отличий от ранее виденной модели линейной регрессии. Это относительно простая глубокая нейронная сеть, состоящая из трёх слоёв. Давайте разберём код построчно. Сначала нам нужен набор данных, который мы сгенерируем, передавая данные x_train вместе с желаемым размером окна, размером пакета и размером буфера для перемешивания. Затем определим модель. Пусть она будет простой: три слоя с 10, 10 и 1 нейронами. Вход сети совпадает с размером окна, и для активации каждого слоя мы используем relu. Затем скомпилируем модель, как и прежде, со среднеквадратичной ошибкой в качестве функцией потерь и стохастическим градиентным спуском в качестве оптимизатора. Наконец, запустим обучение модели в течение 100 эпох, и после нескольких секунд обучения получим результат, похожий на этот. Он довольно хорош. Вычислим среднюю абсолютную ошибку, — и она лучше, чем была раньше, так что это шаг в верном направлении. Но это похоже на тыканье вслепую, особенно при выборе оптимизационной функции. Разве не лучше было бы подбирать оптимальный темп обучения — вместо заданного нами значения? Тогда обучение шло бы эффективнее, давая более совершенную модель. Давайте рассмотрим подход к этой задаче, использующий обратные вызовы — вы их изучали очень давно, в первом курсе. Вот код для той же нейронной сети, но я добавил обратный вызов для подстройки скорости обучения при помощи LearningRateScheduler. Вот этот код. Он будет срабатывать при обратном вызове в конце каждой эпохи. И он будет менять скорость обучения, задавая новое значение, зависящее от номера эпохи. Таким образом, в первую эпоху это 1e-8 * 10**(1/20). А по достижении сотой эпохи, будет 1e-8 * 10**5, где 5 — это 100/20. Так будет при каждом обратном вызове, потому что мы передали эту функцию параметром callbacks метода model.fit. Обучив сеть таким образом, можно отобразить на графике потери в каждую из эпох соответственно скорости обучения в эту эпоху, что даст нам вот такой график. По оси ординат отображается значение функции потерь, а по оси абсцисс — темп обучения. Затем можно выбрать такую нижнюю точку графика, где функция ещё выглядит стабильно, как вот здесь — это примерно 7 на 10 в степени -6. Давайте установим такую скорость обучения и повторно обучим модель. Итак, вот код для той же нейросети, но мы изменили темп обучения, так что обучение будет идти чуть дольше. Давайте посмотрим результаты после обучения в течение 500 эпох. Вот код для вывода графика функции потерь, вычисленной во время обучения, и он даст нам примерно такой график. На первый взгляд выглядит, как будто мы зря тратим время, продолжая обучение после первых, скажем, 10 эпох, но картина искажается из-за того, что в начале потери были очень высоки. Если мы обрежем их и построим график функции потерь для эпох после десятой при помощи такого кода, то график будет говорить уже совсем другое. Мы видим, что функция потерь продолжала падать даже после 500 эпох. И это показывает, что наша сеть действительно очень хорошо учится. А результаты прогнозов накладываются на реальные значения примерно таким образом. Средняя абсолютная ошибка по всем результатам значительно ниже, чем раньше. В следующем видео я подробно пройдусь по этому коду. Используя очень простую DNN, мы значительно улучшили наши результаты. Но это всё ещё простая DNN: она не принимает во внимание последовательности, а в подобных временных рядах значения, непосредственно предшествующие прогнозируемому, могут куда сильнее влиять на него, чем более старые значения. И это идеальные условия для использования РНС, с которыми мы знакомились на курсе обработки естественных языков. На следующей неделе мы их рассмотрим, а пока давайте углубимся в нынешний код.

13(w2)-video10: Deep neural network (18.MLg_4c)

In the previous video, we looked at training a deep neural network to learn, to predict the next value in a Windows sequence. We also looked at some basic hyper parameter tuning to pick a good learning rate for the gradient descent, which then allowed us to further improve the model. In this video, we'll wrap up this week by going through the workbook that shows you how to do all of that. Running this block will set up the data series and all the constants for the Window size and all that. This code will create the Window dataset as before. And here is our DNN where we have three layers in a sequential. The first has ten neurons activated by relu. The second is the same, and the third is a single dense giving us back the predicted value. We'll compile it with means squared error loss and stochastic gradient descent as an optimizer. After 100 epochs it's done, and we can plot the forecast versus the data. Then we can print the mean absolute error. Don't worry if you get a different value, remember there's going to be some random noise in the dataset. If we run this code block we'll retrain over 100 epochs, but we'll use the code back to call the learning rate scheduler, which will then adjust the learning rate over each epoch. When it's done we can then plot the results of the loss against the learning rates. We can then inspect the lower part of the curve before it gets unstable. And we'll come up with the value. In this case it looks to be about two notches to the left of 10 to the minus 5. So I'll say it's 8 times 10 to the minus 6, or thereabouts. I'll then retrain and this time I'll do it for 500 epochs with that learning rate when it's done, I can then plot the loss against the epoch. So we can see how the loss progressed over training time. We can see that it fell sharply and then flattened out. But agin if we remove the first ten epochs, we'll see the latter ones more clearly and it still shows the loss smoothly decreasing at 500 epochs. So it's actually still learning. Let's now plot the forecast against the data and we can see that the prediction still look pretty good. And when we print out the value of the mean absolute error we have improved even further over the earlier value. So that wraps up this week. Go through the workbook yourself and experiment with different neural network definitions, changing around the layers and stuff like that to see if If we can make it even better. Next week we're going to take this to the next level by using neural network types that were current neural networks which have sequencing capabilities built-in. I'll see you there.
---------------------------------------------------------------
В предыдущем видео мы посмотрели, как обучить глубокую нейросеть предсказывать следующее значение в оконной последовательности. Мы также рассмотрели некоторую базовую подстройку гиперпараметров для выбора хорошего темпа обучения при градиентном спуске, что позволило ещё улучшить модель. Этим видео мы завершим неделю разбором блокнота, который покажет вам, как всё это сделать. Запустим этот код, чтобы посмотреть текущую версию TensorFlow. Как и прежде, если вы используете версию старее 2.0, то увидите это здесь. Используйте предыдущую этой ячейку кода, чтобы установить свежую версию TensorFlow или ночную сборку, как у меня. Запуск этого блока подготовит данные и все константы: для размера окна и т.п. Этот код создаст оконный набор данных, как и раньше. А вот наша DNN, в которой три последовательных слоя. Первый имеет десять нейронов с функцией активации relu. Второй слой такой же, а третий — полносвязный слой с одним нейроном, возвращающий предсказанное значение. Скомпилируем модель со среднеквадратичной ошибкой в качестве функции потерь и стохастическим градиентным спуском в качестве оптимизатора. После 100 эпох обучение завершается, и мы можем вывести на график прогноз и реальные данные. А затем вывести среднюю абсолютную ошибку. Не волнуйтесь, если вы получите другое значение: помните, что в наборе данных есть случайный шум. Если выполнить этот блок кода, мы запустим обучение заново в течение 100 эпох, только уже с использованием обратного вызова LearningRateScheduler, который будет менять темп обучения после каждой эпохи. Когда обучение закончится, мы можем построить график зависимости потерь от темпа обучения. Затем изучим нижнюю часть кривой до той точки, где она становится нестабильной, и найдём нужное значение. В данном случае, оно будет примерно на 2 деления левее 1e-5. То есть, 8e-6, или около того. Затем обучим заново, в этот раз — на протяжении 500 эпох, с выбранной скоростью обучения. По завершении построим график функции потерь в зависимости от эпохи, чтобы посмотреть, как потери менялись по мере обучения. Мы видим, что кривая резко упала, а затем вышла в горизонталь. Но если мы снова уберём первые 10 эпох, то сможем лучше разглядеть последующие, и это покажет, что величина потерь плавно снижается даже после 500 эпох. То есть, модель всё ещё учится. Давайте теперь выведем прогнозы в сравнении с реальными данными. Как видим, прогноз всё ещё выглядит очень хорошо. А когда мы выведем значение средней абсолютной ошибки, окажется, что мы ещё сильнее улучшили предыдущий результат. На этом неделя завершается. Самостоятельно пройдитесь по блокноту и поэкспериментируйте с различными моделями нейросетей: изменяйте слои и прочие параметры, чтобы посмотреть, можно ли ещё улучшить результат. На следующей неделе мы выйдем на следующий уровень — используем рекуррентные виды нейросетей, в которых изначально заложена способность работать с последовательностями. До скорых встреч!

14(w2)- Week 2 Quiz: (18.MLg_4c)

1) What is a windowed dataset?:
1. A fixed-size subset of a time series (+)
2. The time series aligned to a fixed shape
3. There's no such thing
4. A consistent set of subsets of a time series
2) What does 'drop_remainder=True' do?:
1. It ensures that all data is used
2. It ensures that all rows in the data window are the same length by cropping data (+)
3. It ensures that the data is all the same shape
4. It ensures that all rows in the data window are the same length by adding data
3) What's the correct line of code to split an n column window into n-1 columns for features and 1 column for a label?:
1. dataset=dataset.map(lambda window:(window[n-1], window[1]))
2. dataset=dataset.map(lambda window:(window[:-1], window[-1:])) (+)
3. dataset=dataset.map(lambda window:(window[-1:], window[:-1]))
4. dataset=dataset.map(lambda window:(window[n], window[1]))
4) What does MSE stand for?:
1. Mean Series error
2. Mean Second error
3. Mean Squared error (+)
4. Mean Slight error
5) What does MAE stand for?:
1. Mean Average error
2. Mean Advanced error
3. Mean Absolute error (+)
4. Mean Active error
6) If time values are in time[], series values are in series[] and we want to split the series into training and validation at time split_time, what is the correct code?:
1.: time_train = time[split_time]
x_train = series[split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
2.: time_train = time[:split_time] (-)
x_train = series[:split_time]
time_valid = time[split_time]
x_valid = series[split_time]
3.: time_train = time[split_time]
x_train = series[split_time]
time_valid = time[split_time]
x_valid = series[split_time]
4.: time_train = time[:split_time] (+)
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
7) If you want to inspect the learned parameters in a layer after training, what's a good technique to use?:
1. Assign a variable to the layer and add it to the model using that variable, Inspect its properties after training. (+)
2. Decompile the model and inspect the output for that layer
3. Run the model with unit data and inspect the output for that layer
4. Iterate through the layers dataset of the model to find the layer you want
8) How do you set the learning rate of the SGD optimizer?:
1. Use the Rate property
2. You can't set it
3. Use the learning_rate property (+)
4. Use the RateOfLearning property
9) If you want to amend the learning rate of the optimizer on the fly, after each epoch. What do you do?:
1. Use a LearningRateScheduler and pass it as a parameter to a callback (-)
2. Callback to a custom function and change the SGD property
3. Use a LearningRateScheduler object in the callbacks namespace and assign that to the callback (+)
4. You can't set it

15(w2)- Week 2 Wrap up: (18.MLg_4c)

You've now explored time series data and seen how to split it into training and validation sets for training a DNN.
But sequence data tends to work better with RNNs. So next week, you're going to look at training a model using RNNs and LSTMs on this data to see what happens.
---------------------------------------------------------------
Теперь вы изучили данные временных рядов и увидели, как разделить их на наборы для обучения и проверки для обучения DNN.
Но данные последовательности, как правило, лучше работают с RNN. Итак, на следующей неделе вы рассмотрите обучение модели с использованием RNN и LSTM на этих данных, чтобы увидеть, что произойдет.

16(w2)- Lecture Notes Week 2: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

17(w2)- Programming Assignment: Forecasting Using Neural Networks: (18.MLg_4c)

Week 2: Predicting time series
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/programming/wiD05/forecasting-using-neural-networks/lab

NEXT week_3 (18.MLg_4c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3)Recurrent Neural Networks for Time Series (18.MLg_4c)

(Рекуррентные нейронные сети для временных рядов)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 17 minutes
Self-study: 1h 26 min
Graded tasks (Tasks to be assessed): 2

(w3) Content (18.MLg_4c)

1.
2.
3.
4.

(w3) Introduction: (18.MLg_4c)

Recurrent Neural networks and Long Short Term Memory networks are really useful to classify and predict on sequential data. This week we'll explore using them with time series...
---------------------------------------------------------------
Рекуррентные нейронные сети и сети долговременной памяти действительно полезны для классификации и прогнозирования последовательных данных. На этой неделе мы рассмотрим их использование с временными рядами...

1(w3)-video1: Week 3 - A conversation with Andrew Ng (18.MLg_4c)

Welcome to week three. In this week, you get to apply RNNs and LSTMs to the time sequence data. Last week you'd applied DNNs to this data. But time series is temporal data, seems like you should be applying a sequence model, like an RNN or an LCM to that. So that's what you do this week. >> Yes, so it's, if you remember in the previous courses, we did natural language processing. And we learned a lot about RNNs and LSTMs there. And how things like the state vector and the cell state in these allow you to maintain context across a series. And with something like a time series data, if you're looking at maybe a 30-day window, or a 30 period window, the likelihood in some time series of data closer to your predictive date, having a bigger impact on data further away, it's there, right? There is a higher likelihood for that. So being able to use RNNs and LSTMs might factor that in to our data to give us a much more accurate prediction. >> Yeah, that's right, looking over a much bigger windows and carrying context from far away. >> Yeah, yeah, exactly, and you know my old favorite LSTMs, and the way they have that cell state, that allows you, we should call it L state, after me. [LAUGH] And the way you have that cell state that allows you to carry context across a long learning process. And I think in some time series data, that would be a really large impact. So for example, like financial data, today's closing price has probably got a bigger impact on tomorrow's closing price than the closing price from 30 days ago, or 60 days ago, or 90 days ago. So being able to use recurrent networks and LSTMs I think it will help us be able to be much more accurate in predicting seasonal data. >> Yeah, cool, and one of the fun things that we'll see this week as well is Lambda layers. >> Lambda layers, yeah. So as a coder, Lambda layers give me comfort. Because sometimes one of the hardest things for me, when I first started doing neural networks was, I write all this code for pre-processing and I write all this code for post-processing. And then I define a neural network and it does all this magic inside a neural network. But I may not have control over what's going on in there. >> It just does whatever it wants to do. >> Or whatever it's been designed to do [LAUGH]. And so, but in Tensorflow and with Keras, Lambda layers allow us to write effectively an arbitrary piece of code as a layer in the neural network. >> So rather than, for example, scaling your data with an explicit pre-processing step and then feeding that data into the neural network, you can instead have a Lambda layer. Basically a Lambda function, an unnamed function, but implemented as a layer in the neural network that resend the data, scales it. And now that pre-processing step is no longer a separate and distinct step, it's part of the neural network. >> So as a programmer that just gives me a lot more comfort, having that kind of control. And it makes it even more fun to be able to build this kind of stuff. >> Yeah, so in this week, you get to apply our RNNs and LCMs to the sequence data. And, as one of the fun features of Tensorflow you learn as well, you also get to implement Lambda layers. Please go on to the next video.
---------------------------------------------------------------
Добро пожаловать на третью неделю. На этой неделе вы научитесь применять РНС и LSTM к временным рядам. На прошлой неделе вы применяли к этим данным глубокую нейросеть, но временные ряды разворачиваются во времени, и к ним лучше применять последовательную модель, такую как РНС или LSTM. Вот этим вы и займётесь на этой неделе. Да, это так. Если помните, на предыдущих курсах мы занимались обработкой естественных языков. И мы многое тогда узнали о РНС и LSTM. И как в них вектор состояния и ячейки памяти позволяют удерживать контекст на протяжении всей последовательности. Когда у нас данные, подобные временному ряду, то при работе с 30-дневным окном, или окном на 30 отсчётов — есть вероятность, что в некоторых рядах данные, лежащие ближе к дате, на которую нужен прогноз, влияют на фактическое значение сильнее, чем более давние данные, верно? Такой расклад вероятнее. И здесь возможность использовать РНС и LSTM может привести к тому, что для таких данных мы получим более точный прогноз. Да, верно, глядя через гораздо большие окна и передавая контекст на большие расстояния. Да, точно, и вам знакомы мои старые любимые LSTM, и то, как в них устроено состояние ячейки состояния (cell state), — может, назвать её L-state, в честь меня? [СМЕХ] Реализация вектора состояний позволяет вам долго удерживать контекст в процессе обучения. И я думаю, что для некоторых временных рядов это должно действительно сильно проявляться. Например, в финансовых данных: сегодняшняя цена закрытия, вероятно, больше влияет на завтрашнюю цену закрытия, чем цена 30 дней назад, или 60, или 90. Так что, думаю, использование рекуррентных сетей и LSTM поможет нам быть куда точнее при прогнозировании сезонных данных. Да, здорово, и среди прочего интересного, на этой неделе мы рассмотрим лямбда-слои. Лямбда-слои, да. Как программисту, лямбда-слои облегчают мне жизнь, ведь, на мой взгляд, одна из самых сложных вещей была в том, что при первых своих пробах с нейросетями я писал кучу кода для предобработки и кучу кода код для постобработки. А затем я строил нейросеть, и внутри неё происходила вся вот эта магия, но у меня не было контроля над тем, что там происходит. Сеть просто делает, что хочет. Или то, для чего она создана. Но в Tensorflow и Keras лямбда-слои позволяют нам прописать практически произвольный кусок кода в качестве слоя нейронной сети. Так, например, вместо того, чтобы масштабировать данные явным образом на этапе предобработки, и затем отправлять их на вход нейросети, вы можете создать лямбда-слой — по сути, лямбда-функцию, анонимную функцию, — встроив её в качестве слоя в нейросеть, чтобы она загружала и масштабировала данные. И тогда предобработка — уже не отдельный независимый этап, а часть нейросети. И как программисту, мне так намного удобней — таким образом это контролировать. И возможность создавать такие штуки делает процесс интереснее. Итак, на этой неделе вы будете применять наши РНС и LSTM для временных рядов, а заодно изучите одну из самых любопытных возможностей TensorFlow — научитесь создавать лямбда-слои. Приглашаем вас перейти к следующему видео.

2(w3)-video2: Conceptual overview (18.MLg_4c)

In the last couple of weeks, you've looked at creating neural networks to forecast time-series data. You started with some simple analytical techniques, which you then extend it to using Machine Learning to do a simple regression. From there you use the DNN that you tweaked a bit to get an even better model. This week, we're going to look at RNNs for the task of prediction. A Recurrent Neural Network, or RNN is a neural network that contains recurrent layers. These are designed to sequentially processes sequence of inputs. RNNs are pretty flexible, able to process all kinds of sequences. As you saw in the previous course, they could've been used for predicting text. Here we'll use them to process the time series. This example, will build an RNN that contains two recurrent layers and a final dense layer, which will serve as the output. With an RNN, you can feed it in batches of sequences, and it will output a batch of forecasts, just like we did last week. One difference will be that the full input shape when using RNNs is three-dimensional. The first dimension will be the batch size, the second will be the timestamps, and the third is the dimensionality of the inputs at each time step. For example, if it's a univariate time series, this value will be one, for multivariate it'll be more. The models you've been using to date had two-dimensional inputs, the batch dimension was the first, and the second had all the input features. But before going further, let's dig into the RNN layers to see how they work. What it looks like there's lots of cells, there's actually only one, and it's used repeatedly to compute the outputs. In this diagram, it looks like there's lots of them, but I'm just using the same one being reused multiple times by the layer. At each time step, the memory cell takes the input value for that step. So for example, it is zero at time zero, and zero state input. It then calculates the output for that step, in this case Y0, and a state vector H0 that's fed into the next step. H0 is fed into the cell with X1 to produce Y1 and H1, which is then fed into the cell at the next step with X2 to produce Y2 and H2. These steps will continue until we reach the end of our input dimension, which in this case has 30 values. Now, this is what gives this type of architecture the name a recurrent neural network, because the values recur due to the output of the cell, a one-step being fed back into itself at the next time step. As we saw in the NLP course, this is really helpful in determining states. The location of a word in a sentence can determine it semantics. Similarly, for numeric series, things such as closer numbers in the series might have a greater impact than those further away from our target value.
---------------------------------------------------------------
В последние пару недель вы познакомились с тем, как создавать нейросеть для предсказания временных рядов. Вы начали с простых аналитических методов, которые потом расширили средствами машинного обучения, именно, простой регрессии. Потом перешли к глубоким нейросетям, которые вы подстраивали, чтобы чуть улучшить модель. На этой неделе мы рассмотрим применение РНС для прогнозирования. Рекуррентные Нейронные Сети, или РНС, — это нейросети, которые содержат рекуррентные слои. Они предназначены для последовательной обработки входной последовательности. РНС — довольно гибкие, и способны обрабатывать все виды последовательностей. Как вы видели в предыдущем курсе, их можно использовать для предсказания текста. Здесь мы будем использовать их для прогнозирования временных рядов. В этом примере мы построим РНС, которая содержит два рекуррентных слоя и последний полносвязный слой, который будет служить выходом. В РНС можно подавать на вход пакеты последовательностей, а она будет выдавать пакеты прогнозов, прямо как у нас было на прошлой неделе. Единственное отличие будет в том, что полная размерность входных данных при использовании РНС будет трёхмерной. Первым измерением будет размер пакета, вторым — отсчёты времени, а третьим — размерность входных данных в каждый отдельный момент времени. Например, если это одновариантный временной ряд, то его размерность будет равна 1, а для многовариантного она будет выше. У моделей, которые вы использовали раньше, вход был двумерный: размер пакета служил первым измерением, а вторым было число входных признаков. Но прежде чем идти дальше, давайте углубимся в слои РНС и посмотрим, как они работают. Они похожи на множество ячеек, которые, в действительности, являются единой ячейкой, которая используется раз за разом для вычисления выхода. На этой диаграмме кажется, будто их множество, но я просто использую одну и ту же ячейку, которую слой использует многократно. На каждом временном шаге ячейка памяти принимает входное значение этого шага, например, в нулевой момент времени это X0, а состояние входа равно 0. Затем сеть вычисляет свой выход для этого шага — в данном случае, Y0, а также вектор состояния H0, который передаётся следующему шагу. H0 подается в ячейку вместе с X1 для получения Y1 и H1, который (H1) затем подаётся в ячейку на следующем шаге вместе с X2, чтобы получить Y2 и H2. И так продолжается шаг за шагом, пока мы не достигнем конца входной последовательности, которая здесь состоит из 30 значений. Вот почему этот тип архитектуры называется рекуррентной нейросетью — потому что данные с выхода ячейки на одном шаге ячейка снова подаёт на свой же вход на следующем шаге. Как мы видели в курсе обработки естественных языков, это действительно полезно при выделении состояний. Положение слова в предложении может определять его семантику. Аналогично и для числовых рядов: более близкие значения в последовательности могут влиять сильнее, чем более отдалённые от нашего целевого значения.

3(w3)-RNN notebook (Lab 1): (18.MLg_4c)

In the next videos, Laurence will demonstrate using RNNs to build your predictive model. You can use the notebook here to follow along.
C4_W3_Lab_1_RNN.ipynb
Ungraded Lab: Using a Simple RNN for forecasting
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W3/ungraded_labs/C4_W3_Lab_1_RNN.ipynb#scrollTo=fO0xC1Cfp5-U
---------------------------------------------------------------

4(w3)-video3: Shape of the inputs to the RNN (18.MLg_4c)

Okay. We've mentioned the shape of the data and the batches that the data is split up into. It's important to take a look at that, and let's dig into that next. The inputs are three dimensional. So for example, if we have a window size of 30 timestamps and we're batching them in sizes of four, the shape will be 4 times 30 times 1, and each timestamp, the memory cell input will be a four by one matrix, like this. The cell will also take the input of the state matrix from the previous step. But of course in this case, in the first step, this will be zero. For subsequent ones, it'll be the output from the memory cell. But other than the state vector, the cell of course will output a Y value, which we can see here. If the memory cell is comprised of three neurons, then the output matrix will be four by three because the batch size coming in was four and the number of neurons is three. So the full output of the layer is three dimensional, in this case, 4 by 30 by 3. With four being the batch size, three being the number of units, and 30 being the number of overall steps. In a simple RNN, the state output H is just a copy of the output matrix Y. So for example, H_0 is a copy of Y_0, H_1 is a copy of Y_1, and so on. So at each timestamp, the memory cell gets both the current input and also the previous output. Now, in some cases, you might want to input a sequence, but you don't want to output on and you just want to get a single vector for each instance in the batch. This is typically called a sequence to vector RNN. But in reality, all you do is ignore all of the outputs, except the last one. When using Keras in TensorFlow, this is the default behavior. So if you want the recurrent layer to output a sequence, you have to specify returns sequences equals true when creating the layer. You'll need to do this when you stack one RNN layer on top of another.
---------------------------------------------------------------
Мы с вами упомянули размерность данных и пакеты, на которые разделены данные. Важно взглянуть на то, что это значит, и давайте следующим разберём этот вопрос. Входные данные являются трехмерными. Так, например, если у нас окно размером в 30 временных отсчётов, и мы собираем их в пакеты по 4, то размерность будет 4 x 30 x 1. На каждом шаге входом в ячейку памяти будет матрица 4 x 1, как здесь. Ячейка также будет принимать матрицу состояний с предыдущего шага. Но, конечно, здесь, на первом шаге, она будет нулевой. Для последующих шагов её значением будет выходное значение ячейки памяти. Но кроме вектора состояний ячейка, разумеется, будет выводить и значение Y, которое мы видим тут. Если ячейка памяти состоит из трёх нейронов, то выходная матрица будет 4 x 3, потому что размер подаваемого пакета равен 4, а нейронов — 3. Таким образом, полный выход слоя будет трёхмерным — в данном случае, 4 x 30 x 3, где 4 — размер пакета, 3 — количество нейронов, а 30 — общее количество шагов. В простой РНС выходной сигнал состояния H является просто копией выходной матрицы Y. Так, например, H0 будет копией Y0, H1 — копией Y1, и так далее. Так что на каждом шаге ячейка памяти получает как текущие входные значения, так и предыдущие выходные. Но в некоторых случаях может потребоваться подать на вход последовательность, ничего не отдавая на выход: нужно получить лишь один вектор для каждого входа в пакете. Это обычно называют РНС типа "многие к одному" (sequence-to-vector). По факту, вы просто игнорируете все выходы, кроме последнего. При использовании Keras в TensorFlow такое поведение используется по умолчанию. И если вы хотите, чтобы рекуррентный слой выводил последовательность, то должны указать параметр return_sequences=True при создании слоя. Обязательно нужно это делать, когда последовательно соединяются два рекуррентных слоя.

5(w3)-video4: Outputting a sequence (18.MLg_4c)

So consider this RNN, these has two recurrent layers, and the first has return_sequences=True set up. It will output a sequence which is fed to the next layer. The next layer does not have return_sequence that's set to True, so it will only output to the final step. But notice the input_shape, it's set to None and 1. TensorFlow assumes that the first dimension is the batch size, and that it can have any size at all, so you don't need to define it. Then the next dimension is the number of timestamps, which we can set to none, which means that the RNN can handle sequences of any length. The last dimension is just one because we're using a univariate time series. If we set return_sequences to true and all recurrent layers, then they will all output sequences and the dense layer will get a sequence as its inputs. Keras handles this by using the same dense layer independently at each time stamp. It might look like multiple ones here but it's the same one that's being reused at each time step. This gives us what is called a sequence to sequence RNN. It's fed a batch of sequences and it returns a batch of sequences of the same length. The dimensionality may not always match. It depends on the number of units in the memory sale. So let's now return to a two-layer RNN that has the second one not return sequences. This will give us an output to a single dense.
---------------------------------------------------------------
Итак, рассмотрим данную РНС, в которой есть два рекуррентных слоя, и у первого установлено return_sequence = True. Этот слой выводит последовательность, которая подаётся на следующий слой. У следующего входа не установлено return_sequence=True, так что он выводит только последний шаг. Но обратите внимание, что размерность входа, input_shape=[None, 1]. TensorFlow предполагает, что первое измерение является размером пакета, а оно может иметь произвольный размер, так что задавать его не нужно. А следующее измерение — это число шагов, которое мы можем установить равным None, чтобы указать, что РНС может обрабатывать последовательности любой длины. Последнее измерение равно 1, потому что мы используем одновариантные временные ряды. Если мы установим return_sequence=True для всех рекуррентных слоев, то все они будут выдавать последовательности, и полносвязный слой получит на вход последовательность. Keras это делает, используя один и тот же полносвязный слой независимо на каждом шаге. На диаграмме это может выглядеть как множество полносвязных слоёв, но это один и тот же слой, повторно используемый на каждом шаге. Тем самым, мы получаем РНС "многие ко многим" (sequence-to-sequence). Ей на вход подаётся пакет последовательностей, и она возвращает пакет последовательностей той же длины. Размерность [входа и выхода] не всегда совпадает. Она зависит от количества нейронов в ячейке памяти. Давайте теперь вернёмся к двухслойной РНС, у которой второй слой возвращает только одно значение. Такая сеть даст только один выход на полносвязный слой.

6(w3)-video5: Lambda layers (18.MLg_4c)

But I'd like to add a couple of new layers to this, layers that use the Lambda type. This type of layer is one that allows us to perform arbitrary operations to effectively expand the functionality of TensorFlow's Keras, and we can do this within the model definition itself. So the first Lambda layer will be used to help us with our dimensionality. If you recall when we wrote the window dataset helper function, it returned two-dimensional batches of Windows on the data, with the first being the batch size and the second the number of timestamps. But an RNN expects three-dimensions; batch size, the number of timestamps, and the series dimensionality. With the Lambda layer, we can fix this without rewriting our Window dataset helper function. Using the Lambda, we just expand the array by one dimension. By setting input shape to none, we're saying that the model can take sequences of any length. Similarly, if we scale up the outputs by 100, we can help training. The default activation function in the RNN layers is tan H which is the hyperbolic tangent activation. This outputs values between negative one and one. Since the time series values are in that order usually in the 10s like 40s, 50s, 60s, and 70s, then scaling up the outputs to the same ballpark can help us with learning. We can do that in a Lambda layer too, we just simply multiply that by a 100. So let's now take a look at what it takes to build out the full RNN so we can start doing some predictions with it. You'll see that in the next video.
---------------------------------------------------------------
Я хотел бы добавить к этой сети пару новых слоёв. Лямбда-слоёв. Этот тип слоя позволяет нам выполнять произвольные операции, тем самым расширяя функциональность Keras в TensorFlow. Эти операции можно задать прямо в определении модели. Первый лямбда-слой поможет нам с размерностью данных. Если помните, мы писали вспомогательную функцию window_dataset, и она возвращала двумерный пакет оконных данных, где первым измерением был размер пакета, а вторым — число отсчётов времени. Но RNN на вход нужны трёхмерные данные: размер пакета, число отсчётов и размерность ряда. При помощи лямбда-слоя можно это исправить, не переписывая нашу вспомогательную функцию. С помощью лямбды мы просто расширим массив на одно измерение. Установив input_shape=None, мы даём понять, что модель может принимать последовательности любой длины. Аналогичным образом, умножив выходной сигнал в 100 раз, мы можем помочь в обучении. Функция активации по умолчанию в рекуррентном слое — tanh, гиперболический тангенс. Его значения лежат в диапазоне от -1 до 1. Поскольку значения временного ряда обычно на порядок больше, составляя десятки: 40-50-60-70, — то пропорциональное увеличение выходных значений до сопоставимых масштабов поможет нам при обучении. Мы можем и это сделать с помощью лямбда-слоя, просто умножая значение на 100. А теперь давайте посмотрим, как построить РНС целиком, чтобы можно было начать прогнозировать с её помощью. Вы увидите это в следующем видео.

7(w3)-video6: Adjusting the learning rate dynamically (18.MLg_4c)

In the previous video, you got a look at RNNs and how they can be used for sequence to vector to sequence to sequence prediction. Let's now take a look at coding them for the problem at hand and seeing if we can get good predictions in our time series using them. One thing you'll see in the rest of the lessons going forward is that I'd like to write a little bit of code to optimize the neural network for the learning rate of the optimizer. Can be pretty quick to train and we can from there save a lot of time in our hyper-parameter tuning. So here's the code for training the RNN with two layers each with 40 cells. To tune the learning rate, we'll set up a callback, which you can see here. Every epoch this just changes the learning rate a little and you can see that setup here while training. I've also introduced a new loss function to use called Huber which you can see here. The Huber function is a loss function that's less sensitive to outliers and as this data can get a little bit noisy, it's worth giving it a shot. If I run this for 100 epochs and measure the loss at each epoch, I will see that my optimum learning rate for stochastic gradient descent is between about 10 to the minus 5 and 10 to the minus 6. So now, I'll set my models compiled with that learning rate and the stochastic gradient descent optimizer. After training for 500 epochs, I will get this chart, with an MAE on the validation set of about 6.35. It's not bad, but I wonder if we can do better. So here's the loss and the MAE during training with the chart on the right is zoomed into the last few epochs. As you can see, the trend was genuinely downward until a little after 400 epochs, when it started getting unstable. Given this, it's probably worth only training for about 400 epochs. When I do that, I get these results. That's pretty much the same with the MAE only a tiny little bit higher, but we've saved 100 epochs worth of training to get it. So it's worth it. A quick look at the training MAE and loss gives us this results. So we've done quite well, and that was just using a simple RNN. Let's see how we can improve this with LSTMs and you'll see that in the next video.
---------------------------------------------------------------
В предыдущем видео вы посмотрели на РНС и на то, как использовать их для предсказаний типа "многие к одному" и "многие ко многим". Давайте теперь посмотрим, как писать код для решения таких задач, и посмотрим, удастся ли с их помощью получить хорошие прогнозы для нашего временного ряда. В следующих наших уроках я стану писать чуть больше кода для оптимизации нейросети с помощью изменения темпа обучения. Это может сильно ускорить обучение, и мы тем самым сможем сэкономить много времени на настройке гиперпараметров. Итак, вот код для обучения РНС с двумя слоями, по 40 нейронов в каждом. Чтобы настроить темп обучения, мы зададим обратный вызов, который вы видите здесь. Он на каждой эпохе немного меняет скорость обучения, так что её шаг меняется от 1e-8 до 1e-6. И вот как он задаётся при запуске обучения. Я также использую новую функцию потерь, которая называется функция Хьюбера, и вы её видите здесь. Функция Хьюбера — это функция потерь, менее чувствительная к выбросам, а поскольку наши данные могут быть шумными, то стоит её попробовать. Если я запущу обучение на протяжении 100 эпох, и измерю значение функции потерь после каждой эпохи, то увижу, что оптимальная скорость обучения для стохастического градиентного спуска находится между 1e-5 и 1e-6. Так что я задам её значение как 5e-5. Теперь я скомпилирую мою модель с этой скоростью обучения и стохастическим градиентным спуском в качестве оптимизатора. После обучения в течение 500 эпох я получу этот график, со средней ошибкой на валидационных данных около 6.35. Не так уж плохо, но мне интересно, можно ли добиться большего успеха. Вот значение функции потерь и MAE в процессе обучения, где масштаб графика справа увеличен, и на нём показаны последние несколько эпох. Как видите, была отчётливая тенденция к снижению потерь почти до 400-й эпохи, когда значение стало нестабильным. Учитывая это, вероятно, стоит обучаться только 400 эпох. Когда я так и сделаю, то получу вот такие результаты. Они почти такие же, и абсолютная ошибка лишь немногим выше, но мы сэкономили 100 эпох обучения, чтобы получить такой результат. Оно того стоило. Беглый взгляд на абсолютную ошибку и потери на тренировочном наборе даёт такие результаты. Итак, мы получили неплохой результат, и это была всего лишь простая РНС. Давайте посмотрим, насколько результат улучшится при использовании LSTM. Увидим это в следующем видео.

8(w3)-More info on Huber loss: (18.MLg_4c)

Please find the Wikipedia page here.
https://en.wikipedia.org/wiki/Huber_loss
---------------------------------------------------------------

9(w3)-video7: LSTM (18.MLg_4c)

In the previous videos, you experimented with using RNNs to predict values in your sequence. The results were good but they did need a bit of improvement as you were hitting strange plateaus in your predictions. You experimented with using different hyperparameters and you saw some improvement, but perhaps a better approach would be to use LSTMs instead of RNNs to see the impact. We'll explore that in this video. If you remember when you looked at RNNs, they looked a little bit like this. They had cells that took batches as inputs or X, and they calculated a Y output as well as the state vector, that fed into the cell along with the next X which then resulted in the Y, and the state vector and so on. The impact of this is that while state is a factor in subsequent calculations, its impacts can diminish greatly over timestamps. LSTMs add the cell state to this that keep a state throughout the life of the training so that the state is passed from cell to cell, timestamp to timestamp, and it can be better maintained. This means that the data from earlier in the window can have a greater impact on the overall projection than in the case of RNNs. The state can also be bidirectional so that state moves forwards and backwards. In the case of texts, this was really powerful. Within the prediction of numeric sequences, it may or may not be, and it'll be interesting to experiment with. I'm not going to go into a lot of detail here but hundreds videos around LSTM are terrific. From there, you can really understand how they work under the hood.
---------------------------------------------------------------
В предыдущих видео вы экспериментировали с РНС, чтобы предсказать значения в последовательности. Результаты получались хорошие, но нуждались в некотором улучшении, потому что в прогнозах возникали странные плато. Вы экспериментировали с использованием разных гиперпараметров, и наблюдали некоторое улучшение, но, возможно, лучше будет использовать LSTM вместо РНС, чтобы посмотреть, что это даст. Это мы и рассмотрим в данном видео. Если вы помните, на вид РНС выглядели примерно так. У них были ячейки, которые принимали пакеты в качестве входных данных, X, и вычисляли выход Y, а также вектор состояния, который подаётся на вход ячейке вместе со следующим X, снова давая на выходе Y и вектор состояния, и так далее. В результате, хотя вектор состояния и влияет на последующие вычисления, но его влияние может сильно уменьшаться с ходом времени. В LSTM для этого есть вектор состояний, который может хранить состояние в течение всего времени обучения, так что состояние передаётся от ячейки к ячейке, от одного момента времени к другому, и оно лучше сохраняется. Это означает, что данные из более ранних значений в пределах окна могут сильнее влиять на все последующие вычисления, чем было в случае РНС. Кроме того, вектор состояний может быть двунаправленным, так что состояние передаётся и вперёд, и назад. В случае текстов, это было очень эффективно. Но в прогнозировании числовых последовательностей это может как давать эффект, так и не давать, и будет интересно с этим поэкспериментировать. Я не буду вдаваться тут в детали, но есть сотни потрясающих видео про LSTM. По ним вы можете полностью разобраться, как LSTM устроены.

10(w3)-video8: Long Short Term Memory (LSTM) (18.MLg_4c)

Please find the link to the LSTM lesson here
https://www.coursera.org/lecture/nlp-sequence-models/long-short-term-memory-lstm-Kxoay
In the last video, you learn about the GRU, the Gated Recurring Unit and how that can allow you to learn very long range connections in a sequence. The other type of unit that allows you to do this very well is the LSTM or the long short term memory units. And this is even more powerful than the GRU, let's take a look. Here the equations from the previous video for the GRU and for the GRU we had a t = c t and two gates the update gate and the relevance gate. c(tilde) t, which is a candidate for replacing the memory cell. And then we use the gate, the update gate gamma Wu to decide whether or not to update c t using c(tilde) t. The LSTM is an even slightly more powerful and more general version of the GRU and it's due to set hook writer and Jurgen Schmidt Huber. And this was a really seminal paper, there's a huge impact on sequence modeling, although I think this paper is one of the more difficult ones to read. It goes quite a lot into the theory of vanishing gradients. And so I think more people have learned about the details of LSTM through maybe other places than from this particular paper, even though I think this paper has had a wonderful impact on the deep learning community. But these are the equations that govern the LSTM, so the will continue to the memory cell c and the candidate value for updating it c(tilde) t will be this. And so notice that for the LSTM, we will no longer have the case that a t is equal to c t. So this is what we use and so this is like the equation on the left except that with now more use a t there or a t-1, c t-1 and we are not using this gamma r this relevance. Although you can have a deviation of the LSTM and we put that back in but with a more common version of the LSTM doesn't bother with that. And then we will have an update gate same as before. So w update and I'm going to use a t-1 here, ct +bu and one new property of the LSTM is instead of having one update gate control both of these terms, we're going to have two separate terms. So instead of gamma u and 1- gamma u were going to have gamma u here and for gate k we should call gamma f. So this gate gamma f is going to be sigmoid of, pretty much what you'd expect. c t plus bf, and then we're going to have a new output gate which is sigmoid of Wo and then again, pretty much what you'd expect plus bo. And then the update value to the memory cell will be c t equals gamma u then this asterisk in those element wise multiplication. There's a vector vector, element wise multiplication plus and instead of one minus gamma u were going to have a separate for gate gamma f times c t-1. So this gives the memory cell the option of keeping the old value c t-1 and then just adding to it this new value c(tilde) t. So use a separate update and forget gates right? So this stands on update. Forget and output gates and then finally instead of 80 equals c t. Is a t equal to the output gate element wise multiply with c t. So these are the equations that govern the LSTM. And you can tell it has three gates instead of two. So it's a bit more complicated and places against in slightly different places. So here again are the equations governing the behavior of the LSTM. Once again it's traditional to explain these things using pictures, so let me draw one here. And if these pictures are too complicated don't worry about it, I probably find the equations easier to understand than the picture but just show the picture here for the intuitions it conveys. The particular picture here was very much inspired by a blog post due to Chris Kohler titled Understanding LSTM networks. And the diagram drawn here is quite similar to one that he drew in his blog post. But the key things to take away from this picture or maybe that you use a t-1 and x t to compute all the gate values. So in this picture you have a t-1 and x t coming together to compute a forget gate to compute the update gates and the computer the output gate. And they also go through a tarnish to compute a c(tilde) t. And then these values are combined in these complicated ways with element wise multiplies and so on to get a c t from the previous c t -1. Now one element of this is interesting is if you hook up a bunch of these in parallel so that's one of them and you connect them, connect these temporarily. So there's the input x 1, then x 2, x 3. So you can take these units and just hook them up as follows where the output a for a period of time, 70 input at the next time set. And similarly for C and I've simplified the diagrams a little bit at the bottom. And one cool thing about this, you notice is that this is a line at the top that shows how so long as you said the forget and the update gates, appropriately, it is relatively easy for the LSTM to have some value C0 and have that be passed all the way to the right to have, maybe C3 equals C0. And this is why the LSTM as well as the GRU is very good at memorizing certain values. Even for a long time for certain real values stored in the memory cells even for many, many times steps. So that's it for the LSTM, as you can imagine, there are also a few variations on this that people use. Perhaps the most common one, is that instead of just having the gate values be dependent only on a t-1, xt. Sometimes people also sneak in there the value c t -1 as well. This is called a peephole connection. Not a great name maybe, but if you see peephole connection, what that means is that the gate values may depend not just on a t-1 but and on x t but also on the previous memory cell value. And the peephole connection can go into all three of these gates computations. So that's one common variation you see of LSTMs one technical detail is that these are say 100 dimensional vectors. If you have 100 dimensional hidden memory cell union. So is this and so say fifth element of c t-1 affects only the fifth element of the correspondent gates. So that relationship is 1 to 1 where not every element of the 100 dimensional c t-1 can affect all elements of the gates, but instead the first element of c t-1 affects the first element of the gates. Second element affects second elements and so on. But if you ever read the paper and see someone talk about the peephole connection, that's what they mean, that c t -1 is used to affect the gate value as well. So that's it for the LSTM, when should you use a GRU and when should you use an LSTM. There is a widespread consensus in this. And even though I presented GRUs first in the history of deep learning, LSTMs actually came much earlier and then GRUs were relatively recent invention that were maybe derived as partly a simplification of the more complicated LSTM model. Researchers have tried both of these models on many different problems and on different problems the different algorithms will win out. So there isn't a universally superior algorithm, which is why I want to show you both of them. But I feel like when I am using these, the advantage of the GRU is that it's a simpler model. And so it's actually easier to build a much bigger network only has two gates, so computation runs a bit faster so it scales the building, somewhat bigger models. But the LSTM is more powerful and more flexible since there's three gates instead of two. If you want to pick one to use, I think LSTM has been the historically more proven choice. So if you had to pick one, I think most people today will still use the LSTM as the default first thing to try. Although I think the last few years GRUs have been gaining a lot of momentum and I feel like more and more teams are also using GRUs because they're a bit simpler but often were, just as well and it might be easier to scale them to even bigger problems. So that's it for LSTMs with either GRUs or LSTMS, you'll be able to build new networks that can capture much longer range dependencies.
---------------------------------------------------------------
В последнем видео вы узнаете о GRU, Gated Recurring Unit и о том, как это может позволить вам изучать соединения очень дальнего действия в последовательности. Другой тип устройства, который позволяет вам делать это очень хорошо, — это LSTM или блоки долговременной кратковременной памяти. А это даже мощнее ГРУ, давайте посмотрим. Здесь уравнения из предыдущего видео для ГРУ и для ГРУ у нас были t = c t и два вентиля: вентиль обновления и вентиль релевантности. c(тильда) t, который является кандидатом на замену ячейки памяти. И затем мы используем ворота, ворота обновления гамма Wu, чтобы решить, обновлять ли c t с помощью c(tilde) t. LSTM — это даже немного более мощная и более общая версия GRU, созданная писателем set hook и Юргеном Шмидтом Хубером. И это была действительно основополагающая статья, она оказала огромное влияние на моделирование последовательностей, хотя я думаю, что эта статья одна из самых сложных для чтения. Это довольно много связано с теорией исчезающих градиентов. И поэтому я думаю, что больше людей узнали о деталях LSTM, возможно, из других источников, а не из этой конкретной статьи, хотя я думаю, что эта статья оказала замечательное влияние на сообщество глубокого обучения. Но это уравнения, которые управляют LSTM, поэтому они будут продолжаться до ячейки памяти c, а значение кандидата для ее обновления c (тильда) t будет таким. Итак, обратите внимание, что для LSTM у нас больше не будет случая, когда a t равно c t. Итак, это то, что мы используем, и это похоже на уравнение слева, за исключением того, что теперь больше используется t там или t-1, c t-1, и мы не используем эту гамму или эту релевантность. Хотя у вас может быть отклонение от LSTM, и мы вернем его, но с более распространенной версией LSTM это не беспокоит. И тогда у нас будут такие же ворота обновлений, как и раньше. Итак, w update, и я собираюсь использовать здесь t-1, ct +bu и одно новое свойство LSTM — вместо того, чтобы один шлюз обновления контролировал оба этих термина, у нас будет два отдельных термина. Таким образом, вместо gamma u и 1-gamma u здесь будет гамма u, а для ворот k мы должны назвать gamma f. Таким образом, эта гамма ворот f будет сигмовидной, чего и следовало ожидать. c t плюс bf, а затем у нас будет новый выходной вентиль, который является сигмоидой Wo, и опять же, почти то, что вы ожидаете, плюс bo. И тогда значение обновления в ячейке памяти будет равно ct равно gamma u, а затем этой звездочке в этих поэлементных умножениях. Есть векторный вектор, поэлементное умножение плюс и вместо одного минус гамма u будет иметь отдельную для ворот гамму f раз c t-1. Таким образом, это дает ячейке памяти возможность сохранить старое значение c t-1, а затем просто добавить к нему это новое значение c(тильда) t. Так что используйте отдельное обновление и забудьте о гейтах, верно? Так что это стоит на обновлении. Забудьте и выведите гейты и тогда, наконец, вместо 80 будет равно c t. Является ли a t равным элементу выходного затвора, умноженным на c t. Итак, это уравнения, которые управляют LSTM. И вы можете сказать, что у него трое ворот вместо двух. Так что это немного сложнее и размещается в немного разных местах. Итак, здесь снова приведены уравнения, управляющие поведением LSTM. Опять же, традиционно объяснять эти вещи с помощью картинок, так что позвольте мне нарисовать одну здесь. И если эти изображения слишком сложны, не беспокойтесь об этом, я, вероятно, нахожу уравнения более понятными, чем изображение, но просто покажите изображение здесь для интуитивного понимания, которое оно передает. Конкретное изображение здесь было очень вдохновлено сообщением в блоге Криса Колера под названием «Понимание сетей LSTM». И схема, нарисованная здесь, очень похожа на ту, которую он нарисовал в своем блоге. Но ключевые вещи, которые можно извлечь из этой картины, или, может быть, то, что вы используете t-1 и x t для вычисления всех значений вентиля. Итак, на этом рисунке у вас есть t-1 и x t, которые объединяются для вычисления вентиля забывания для вычисления вентиля обновления, а компьютер — выходного вентиля. И они также проходят через потускнение, чтобы вычислить c (тильду) t. А затем эти значения комбинируются сложными способами с поэлементным умножением и так далее, чтобы получить значение c t из предыдущего c t -1. Теперь интересен один элемент: если вы соедините их несколько параллельно, так что это один из них, и вы соедините их, соедините их временно. Итак, есть вход x 1, затем x 2, x 3. Итак, вы можете взять эти единицы и просто подключить их следующим образом, где выход a за определенный период времени, 70 вход в следующий раз. И аналогично для C, и я немного упростил диаграммы внизу. И одна интересная вещь в этом, как вы заметили, заключается в том, что это строка вверху, которая показывает, как долго, как вы сказали, ворота «забыть» и «обновить», соответственно, для LSTM относительно легко иметь некоторое значение C0 и иметь это пройти весь путь вправо, может быть, C3 равно C0. И именно поэтому LSTM, а также GRU очень хорошо запоминают определенные значения. Даже в течение длительного времени для некоторых реальных значений, хранящихся в ячейках памяти даже для много-много раз шагов. Вот и все, что касается LSTM, как вы можете себе представить, есть также несколько вариантов, которые люди используют. Возможно, самый распространенный из них заключается в том, что вместо того, чтобы значения вентиля зависели только от t-1, xt. Иногда туда же подсовывают и значение c t -1. Такое соединение называется глазком. Может быть, не очень удачное название, но если вы видите глазок, это означает, что значения вентилей могут зависеть не только от t-1, но и от x t, но также и от предыдущего значения ячейки памяти. И глазок может использоваться во всех трех вычислениях ворот. Итак, это одна из распространенных вариаций LSTM, которую вы видите. Одна техническая деталь заключается в том, что это, скажем, 100-мерные векторы. Если у вас есть 100-мерный союз скрытых ячеек памяти. Так вот этот и так сказать пятый элемент c t-1 влияет только на пятый элемент соответствующих вентилей. Таким образом, это отношение 1 к 1, где не каждый элемент 100-мерного c t-1 может влиять на все элементы ворот, а вместо этого первый элемент c t-1 влияет на первый элемент ворот. Второй элемент влияет на вторые элементы и так далее. Но если вы когда-нибудь прочитаете статью и увидите, что кто-то говорит о подключении через глазок, они имеют в виду, что c t -1 также используется для воздействия на значение затвора. Вот и все для LSTM, когда вы должны использовать GRU и когда вы должны использовать LSTM. В этом существует широко распространенное мнение. И хотя я представил GRU первыми в истории глубокого обучения, LSTM на самом деле появились намного раньше, а затем GRU были относительно недавним изобретением, которое, возможно, было получено как частичное упрощение более сложной модели LSTM. Исследователи опробовали обе эти модели на множестве разных задач, и в разных задачах выигрывали разные алгоритмы. Итак, не существует универсально превосходного алгоритма, поэтому я хочу показать вам оба из них. Но мне кажется, что когда я их использую, преимущество ГРУ в том, что это более простая модель. И поэтому на самом деле проще построить гораздо большую сеть, имеющую только два входа, поэтому вычисления выполняются немного быстрее, поэтому они масштабируют здание, несколько более крупные модели. Но LSTM мощнее и гибче, поскольку у него три ворот вместо двух. Если вы хотите выбрать один для использования, я думаю, что LSTM был исторически более проверенным выбором. Так что, если вам нужно было выбрать один, я думаю, что большинство людей сегодня по-прежнему будут использовать LSTM по умолчанию в первую очередь, чтобы попробовать. Хотя я думаю, что за последние несколько лет GRU набирают обороты, и я чувствую, что все больше и больше команд также используют GRU, потому что они немного проще, но часто так и было, и их может быть легче масштабировать для еще большие проблемы. Вот и все, что касается LSTM с GRU или LSTMS, вы сможете создавать новые сети, которые могут захватывать гораздо более дальние зависимости.

11(w3)-LSTM notebook (Lab 2): (18.MLg_4c)

You can use the notebook here to follow along the LSTM coding demo in the next video.
C4_W3_Lab_2_LSTM.ipynb
Ungraded Lab: Using a multi-layer LSTM for forecasting
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W3/ungraded_labs/C4_W3_Lab_2_LSTM.ipynb#scrollTo=sV_nvXSQGJPK
---------------------------------------------------------------

12(w3)-video9 Coding LSTMs (18.MLg_4c)

So let's now take a look at some code for LSTMs and how they can work with the data that we've been playing with all week. So here's the update to our code to use LSTMs. Let's unpack it and take a look at the interesting parts. First of all is the tf.keras.backend.clear_session, and this clears any internal variables. That makes it easy for us to experiment without models impacting later versions of themselves. After the Lambda layer that expands the dimensions for us I've added a single LSTM layer with 32 cells. I've also made a bidirectional to see the impact of that on a prediction. The output neuron will give us our prediction value. I'm also using a learning rate of one times 10 _ minus six and that might be worth experimenting with too. So here's the results of running this LSTM on the synthetic data that we've been using throughout the course. The plateau under the big spike is still there and are MAE is in the low sixes. It's not bad, it's not great, but it's not bad. The predictions look like there might be a little bit on the low side too. So let's edit our code to add another LSTM to see the impact. Now you can see the second layer and note that we had to set return sequences equal to true on the first one in order for this to work. We train on this and now we will see the following results. Here's the chart. Now it's tracking much better and closer to the original data. Maybe not keeping up with the sharp increase but at least it's tracking close. It also gives us a mean error that's a lot better and it's showing that we're heading in the right direction. If we edit our source to add a third LSTM layer like this, by adding the layer and having the second layer return sequences is true we can then train and run it, and we'll get the following output. So that's it for looking at LSTMs and predicting our sequences. In the next video you'll take a look at using convolutions to see what the impact will be on using them for predicting time-series content.
---------------------------------------------------------------
Теперь давайте взглянем на код для LSTM, и на то, как LSTM справится с данными, с которыми мы играем всю эту неделю. Итак, вот новая редакция нашего кода, с использованием LSTM. Давайте присмотримся поближе к интересным фрагментам. Прежде всего, это tf.keras.backend.clear_session, данный вызов очищает все внутренние переменные. Это позволяет нам экспериментировать так, чтобы модели не влияли на свои же более поздние версии. После лямбда-слоя, который увеличивает размерность данных, я добавил один слой LSTM с 32 ячейками. Я также сделал его двунаправленным, чтобы посмотреть, как это повлияет на прогнозирование. Выходной нейрон будет давать нам прогнозируемое значение. Я также использую скорость обучения, равную 1e-6, и, возможно, с ней тоже стоит поэкспериментировать. Итак, вот результаты запуска этой LSTM на тех синтетических данных, которые мы используем в течение всего курса. Плато перед резким пиком по-прежнему здесь, и ошибка чуть больше 6. Не так уж плохо, но и отличным не назовёшь. Предсказания выглядят так, словно они слегка занижаются. Давайте изменим наш код, добавив еще одну LSTM, и посмотрим, как это повлияет. Теперь вы видите второй слой, — обратите внимание, что нам пришлось задать параметр return_sequences=True для первого слое, чтобы всё работало. Обучаем эту сеть и видим следующие результаты. Вот график. Теперь сеть прогнозирует гораздо лучше и ближе к исходным данным. Возможно, не угадывая резкие всплески, но, как минимум, приближаясь к ним. Также мы получаем намного лучшую абсолютную ошибку, и это указывает, что мы движемся в верном направлении. Если изменить наш код, добавив третий слой LSTM, вот так, добавив слой и задав и для второго слоя return_sequences=True, то можно затем обучить и прогнать модель, и получить вот такой результат. Разница не особо велика, и абсолютная ошибка ухудшилась. Итак, мы попробовали предсказать нашу последовательность с помощью LSTM. В следующем видео вы увидите, как использовать свёртки, и каков будет эффект от их использования для предсказания временных рядов.

13(w3)- Week 3 Quiz: (18.MLg_4c)

1) If X is the standard notation for the input to an RNN, what are the standard notations for the outputs?:
1. Y
2. H
3. Y(hat) and H (+)
4. H(hat) and Y
2) What is a sequence to vector if an RNN has 30 cells numbered 0 to 29:
1. The Y(hat) for the second cell
2. The Y(hat) for the last cell (+)
3. The total Y(hat) for all cells
4. The average Y(hat) for all 30 cells
3) What does a Lambda layers in a neural network do?:
1. There are no Lambda layers in a neural network
2. Allows you to execute arbitrary code while training (+)
3. Changes the shape of the input or output data
4. Pauses training without a callback
4) What does the axis parameter of tf.expand_dims do? :
1. Defines the dimension index at which you will expand the shape of the tensor (+)
2. Defines if the tensor is X or Y
3. Defines the axis around which to expand the dimensions
4. Defines the dimension index to remove whine you expand the tensor
5) A new loss function was introduced in this module, name after a famous statistician. What is it called?:
1. Hubble loss
2. Huber loss (+)
3. Hawking loss
4. Hyatt loss
6) What's the primary difference between a simple RNN and an LSTM?:
1. In addition to the H output, LSTMs have a cell state that runs across all cells (+)
2. LSTMs have a single output, RNNs have multiple
3. In addition to the H output, Rnns have a cell state that runs across all cells
4. LSTMs have multiple outputs, RNNs have a single one
7) If you want to clear out all temporary variables that tensorflow might have from previous sessions, what code do you run?:
1. tf.cache.backend, clear_session()
2. tf.keras.clear_session (-)
3. tf.chache.clear_session()
4. tf.keras.backen.clear_session() (+)
8) What happens if you define a neural network with these two layers?:
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Dense(1)
1. Your model will compile and run correctly (-)
2. Your model will fail because you need return_sequences=True after each LSTM layer
3. Your model will fail because you need return_sequences=True after the first LSTM layer (+)
4. Your model will fail because you have the same number of cells in each LSTM

14(w3)- Week 3 Wrap up: (18.MLg_4c)

Now that you've built on your DNNs with RNNs and LSTMs, it's time to put it all together using CNNs and some real world data.
Next week you'll do that, exploring the prediction of sunspot data from a couple of hundred years worth of measurements!
---------------------------------------------------------------
Теперь, когда вы построили свои DNN с помощью RNN и LSTM, пришло время собрать все это вместе, используя CNN и некоторые данные из реального мира.
На следующей неделе вы сделаете это, исследуя предсказание данных о солнечных пятнах на основе измерений за пару сотен лет!

15(w3)- Lecture Notes Week 3: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

16(w3)- Programming Assignment: Forecast using RNNs or LSTMs: (18.MLg_4c)

Week 3: Using RNNs to predict time series
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/programming/30QuE/forecast-using-rnns-or-lstms/lab?path=%2Fnotebooks%2FC4W3_Assignment.ipynb

NEXT week_4 (18.MLg_4c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w4)Real-world time series data (18.MLg_4c)

(Реальные данные временных рядов)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 22 minutes
Self-study: 2h 38 min
Graded tasks (Tasks to be assessed): 2

(w4) Content (18.MLg_4c)

1. 2. 3. 4.

(w4) Introduction: (18.MLg_4c)

On top of DNNs and RNNs, let's also add convolutions, and then put it all together using a real-world data series -- one which measures sunspot activity over hundreds of years, and see if we can predict using it.
---------------------------------------------------------------
Вдобавок к DNN и RNN давайте также добавим свертки, а затем соберем все вместе, используя ряды реальных данных, которые измеряют активность солнечных пятен за сотни лет, и посмотрим, сможем ли мы предсказать их использование.

1(w4)-video1: Week 4 - A conversation with Andrew Ng (18.MLg_4c)

Welcome to the final week of this final course of this specialization. There's a lot happening this week that I hope you find fun and exciting. You get to take sunspot data, the real data and apply a 1D convnet to that. So this is generalization of the 2D curve you see, and on top of that and LSTM and on top of that a dense neural networks. So a lot of pieces you've learned will come together to help you build an effective sunspot prediction. This specialization was called Tensor Flow in practice. So one of the things that Andrew and I have been really excited about is helping you to be able to put everything that you've been learning in this specialization into practice. So in this course we've been using synthetic data for the last three weeks, but we're now taking you away from the synthetic data and giving you the real-world sunspot data that Andrew mentioned; convolutional neural networks and 1D cams, LSTMs, deep neural networks, we'll be able to mash them all together and hopefully come up with some nice prediction engines for sunspot activity. So by the end of this week, you have built a pretty sophisticated neural network model that it puts together many of these pieces. By doing that, I hope you may be able to start seeing how you could maybe assemble these pieces you've learned in Tensor Flow to build other rich neural networks as well. So please go on to the next video.
---------------------------------------------------------------
Добро пожаловать на последнюю неделю завершающего курса этой специализации. На этой неделе будет масса всего, и я надеюсь, что вам будет интересно. Вы возьмёте данные о пятнах на Солнце, реальные данные, — и примените к ним одномерные свёртки. Тем самым, мы обобщим двумерные свёртки, и поверх них будет идти LSTM, а поверх неё — полносвязная нейросеть. Множество изученных вами частей будет сведено воедино, чтобы вы могли эффективно прогнозировать солнечную активность. Эта специализация называется "TensorFlow на практике". Так что мы с Эндрю очень рады возможности помочь вам собрать воедино всё то, что вы изучали на протяжении всей этой специализации, и применить это на практике. В течение предыдущих трёх недель этого курса мы использовали синтетические данные, но теперь мы расстаёмся с синтетическими данными и даём вам реальные данные по солнечной активности, о которых сказал Эндрю. Свёрточные нейросети, LSTM, глубокие нейросети — мы хорошенько всё это замесим и будем надеяться, что выйдет хороший инструмент для прогнозирования солнечной активности. Итак, к концу этой недели у вас будет готова довольно сложная модель на основе нейросетей, которая сведёт воедино многие из перечисленных частей. Я надеюсь, что разрабатывая её, вы начнёте понимать, как собирать все эти части TensorFlow, которые вы изучили, чтобы строить и другие сложные нейросети. Приглашаем вас перейти к следующему видео.

2(w4)-video2: Convolutions (18.MLg_4c)

Last week, we looked at recurrent neural networks including a simple RNN and an LSTM. You saw how they could be useful in learning a sequence like the one that we've been looking at. And how the LSTMs removed some of the issues we had with an RNN. This week, you'll go one step further, combining convolutions with LSTMs to get a very nicely fitting model. We'll then apply that to real world data instead of this synthetic data set that we've been working on since the beginning of this course. Here's the LSTM that you looked at last week, except that I've added something at the beginning of the sequential stack. It's a Conv1D where we'll try to learn 32 filters. It's a one dimensional convolution. So we'll take a five number window and multiply out the values in that window by the filter values, in much the same way as image convolutions are done. Check back to the convolutions course to learn more about that.
---------------------------------------------------------------
На прошлой неделе мы рассмотрели рекуррентные нейросети, включая простую РНС и LSTM. Вы видели, насколько они полезны при обучении на последовательностях, вроде той, которая у нас была. И видели, как LSTM устраняют некоторые из проблем, возникавших с РНС. На этой неделе вы пойдёте еще дальше, объединяя свёртки с LSTM и получая в результате модель, весьма близкую к данным. Затем мы применим её к реальным данным вместо синтетических, над которыми мы работали с начала данного курса. Вот та LSTM, рассмотренная на прошлой неделе, только я добавил ещё кое-что в самом начале цепочки слоёв. Это слой Conv1D, в котором мы будем обучать 32-м фильтра. Это одномерная свёртка. Мы возьмём окно из пяти чисел и умножим значения в окне на значения фильтра, практически так же, как мы делали со свёртками на изображениях. Обратитесь к курсу по свёрточным сетям, чтобы больше узнать об этом.

3(w4)-Convolutional neural networks course: (18.MLg_4c)

More information on CNNs can be found on Andrews course within the Deep Learning Specialization.
If you are curious about the content and would like to learn more, here is the link to the course.
https://www.coursera.org/learn/convolutional-neural-networks
---------------------------------------------------------------

4(w4)-video3: Bi-directional LSTMs (18.MLg_4c)

One important note is that while we got rid of the Lambda layer that reshaped the input for us to work with the LSTM's. So we're actually specifying an input shape on the curve 1D here. This requires the windowed dataset helper function that we've been working with all along. Also similar to last week, the code will attempt lots of different learning rates changing them epoch by epoch and plotting the results. With this data and the convolutional and LSTM-based network, we'll get a plot like this. It clearly bottoms are around 10 to the minus five after which it looks a bit unstable, so we'll take that to be our desired learning rates. Thus when we define the optimizer will set the learning rate to be 1e-5 as shown here. When we train for 500 epochs we'll get this curve. It's a huge improvement over earlier. The peak has lost its plateau but it's still not quite right, it's not getting high enough relative to the data. Now of course noise is a factor and we can see crazy fluctuations in the peak caused by the noise, but I think our model could possibly do a bit better than this. Our MAE is below five, but I would bet that outside of that first peak is probably a lot lower than that. One solution might be to train a little bit longer. Even though our MAE loss curves look flat at 500 epochs, we can see when we zoom in that they're slowly diminishing. The network is still learning albeit slowly. Now one method would be to make your LSTMs bidirectional like this. When training, this looks really good giving very low loss in MAE values sometimes even less than one. But unfortunately it's overfittingng when we plot the predictions against the validation set, we don't see much improvement and in fact, you might need to tweak some of the parameters to avoid overfitting. Some of the problems are clearly visualize when we plot the loss against the MAE, there's a lot of noise and instability in there. One common cause for small spikes like that is a small batch size introducing further random noise. I won't go into the details here, but if you check out Andrew's videos and his course on optimizing for gradient descent, there's some really great stuff in there. One hint was to explore the batch size and to make sure it's appropriate for my data. So in this case it's worth experimenting with different batch sizes. So for example experimented with different batch sizes both larger and smaller than the original 32, and when I tried 16 you can see the impact here on the validation set, and here on the training loss and MAE data. Okay so by combining CNNs and LSTMs we've been able to build our best model yet, despite some rough edges that could be refined. In the next video, we'll step through a notebook that trains with this model so that you can see it for yourself, and also we'll maybe learn how to do some fine-tuning to improve the model even further. After that, we'll take the model architecture and apply it to some real-world data instead of the synthetic ones that you've been using all along.
---------------------------------------------------------------
Обратите внимание: мы избавились от лямбда-слоя, менявшего размерность входа для работы с LSTM. Поэтому теперь мы определяем размерность входа в слой Conv1D вот здесь. Для этого нужно изменить вспомогательную функцию windowed_datasetet, с которой мы работали всё это время. Мы просто будем использовать в ней tf.expand_dims, чтобы увеличить размерность ряда (на 1) перед тем, как работать с ним дальше. Как и на прошлой неделе, в код мы будем пробовать множество различных темпов обучения, изменяя их от эпохи к эпохе и выводя на график результаты. На этих данных для нейросети со свёртками и LSTM у нас получится график вроде этого. В нём отчётливый минимум в районе 1e-5, после которого результат выглядит несколько нестабильным, так что мы возьмём это число в качестве нужного темпа обучения. Таким образом, во время инициализации оптимизатора мы зададим темп обучения, равный 1e-5, как показано здесь. После обучения в течение 500 эпох мы получим такую кривую. Это огромный прогресс по сравнению с тем, что было раньше. Пик [слева] перестал быть похожим на плато, но прогноз всё ещё недостаточно точен, он всё ещё недостаточно тесно следует за данными. Конечно, шум — это важный фактор, и мы видим сумасшедшие флуктуации, вызванные шумом, в окрестностях максимума, но я думаю, наша модель, возможно, могла бы работать получше, чем сейчас. Наша абсолютная ошибка меньше 5, но готов побиться об заклад, что вне окрестностей первого пика она намного ниже. Одним из решений могло бы быть более продолжительное обучение. Хотя функция потерь и выглядит плоской в течение 500 эпох, но если увеличить график, мы видим, что она понемногу уменьшается. Сеть всё ещё учится, но медленно. Ещё один возможный способ — сделать LSTM-слои двунаправленными, как здесь. При обучении прогресс выглядит очень хорошо, давая очень низкую абсолютную ошибку — иногда даже меньше 1. Но, к сожалению, модель переобучается, и когда мы получаем прогнозы на валидационных данных, то не видим улучшения — более того, абсолютная ошибка даже ухудшилась. Тем не менее, это шаг в верном направлении, и со временем мы рассмотрим подобную архитектуру, но, возможно, потребуется подстроить некоторые параметры, чтобы избежать переобучения. Некоторые проблемы явно видны, когда мы строим график абсолютной ошибки и функции потерь: картина неустойчивая, с большим количеством шума. Одна из распространенных причин появления подобных небольших пиков — это маленький размер пакета, который дополнительно вносит случайный шум. Я не буду здесь вдаваться в подробности, но если вы посмотрите видео Эндрю из его курса по оптимизации градиентного спуска, то там есть очень полезные вещи. И один из советов — проверить размер пакета и убедиться, что он соответствует данным. Так что, стоит поэкспериментировать с разными размерами пакета. Например, проверить разные размеры пакета, как больше, так и меньше, чем исходные 32, — и когда я взял размер 16, то посмотрите, какой эффект это произвело на предсказания на валидационных данных. А вот какими стали функция потерь и абсолютная ошибка на обучающей выборке. Итак, объединяя свёрточные сети и LSTM, мы смогли построить нашу лучшую на данный момент модель, несмотря на некоторые шероховатости, которые можно отполировать. В следующем видео мы пройдёмся пошагово по блокноту, в котором обучается эта модель, чтобы вы могли увидеть всё своими глазами, и, возможно, мы также узнаем, как подстраивать параметры, ещё более улучшая модель. После этого мы возьмём архитектуру этой модели, и применим её к реальным данным вместо синтетических, которыми пользовались весь этот курс.

5(w4)-vide4: More on batch sizing (18.MLg_4c)

Please find more information here
https://www.youtube.com/watch?v=4qJaSmvhxi8
---------------------------------------------------------------

6(w4)-Convolutions with LSTM notebook (Lab 1): (18.MLg_4c)

The next video is a screencast demonstrating how to use convolution layers with the LSTM network you built last week. You can find the link to the notebook here.
C4_W4_Lab_1_LSTM.ipynb
Ungraded Lab: Using Convolutions with LSTMs
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W4/ungraded_labs/C4_W4_Lab_1_LSTM.ipynb#scrollTo=GYEYC1orNFdN
---------------------------------------------------------------

7(w4)-vide5: Convolutions with LSTM (18.MLg_4c)

In the previous video, you saw how you could stack a convolutional layer with LSTMs and bidirectional LSTMs to do sequence prediction. In this video, we'll go through a workbook for this, which you can then try for yourself later. This code will generate the synthetic time series for you, and this code will turn the array of data into a dataset for training. Note that we've expanded the dimensions on the first line. This first copy of the neural network has run for a quick 100 Epoch run to try and pick the optimum learning rate for the optimizer. When it's done, we'll plot the results and we'll see the optimum value, so we'll set that on the SGD for the next training run. We'll train for 500 Epochs now and keep an eye on our loss and our mae. When it's done, we'll run our forecast and plot the results. Already the curve is looking much better and the plateau that we'd seen in previous training has vanished, and our mae is low, it's just above five at the validation set. Finally, if we plot our training loss and mae, we also see a healthy curve downwards.
---------------------------------------------------------------
В предыдущих видео вы видели, как сочетать свёрточный слой с LSTM или двунаправленным LSTM для прогнозирования значений ряда. В этом видео мы пройдёмся по подготовленному для этого пособию, а затем вы сможете поработать с ним самостоятельно. Как всегда, давайте проверим, установлен ли у вас TensorFlow 2. Если нет, установите самую свежую ночную сборку или последний релиз с tenorflow.org. Когда вы убедитесь, что у вас версия 2, этот код сгенерирует вам синтетический временной ряд, а вот этот код преобразует массив данных в набор для обучения. Обратите внимание, что в первой строке мы увеличиваем размерность данных. Эта вспомогательная функция вычислит нам прогноз после обучения. Первый экземпляр нейросети обучается недолгие 100 эпох, чтобы проверить и задать в оптимизаторе оптимальный темп обучения. Когда она закончит работу, мы выведем график с результатами и увидим, что 1e-5 — оптимальное значение, так что мы передадим его в стохастический градиентный спуск на следующем прогоне. В этот раз мы будем обучаться 500 эпох и следить за функцией потерь и абсолютной ошибкой. Когда обучение закончится, мы посчитаем наши прогнозы и построим график с результатами. Кривая уже выглядит намного лучше, и плато, которое мы видели на предыдущих моделях, исчезло. Абсолютная ошибка тоже низкая, она лишь немногим выше 5 на валидационных данных. Наконец, если мы построим график функции потерь и абсолютной ошибки, то увидим хорошие нисходящие кривые.

8(w4)-vide6: Real data - sunspots (18.MLg_4c)

Over the last few weeks, you looked at time-series data and examined a few techniques for forecasting that data including statistical analysis, linear regression, and machine-learning with both deep learning networks and recurrent neural networks. But now we're going to move beyond the synthetic data to some real-world data and apply what we've learned to creating forecasts for it. Let's start with this dataset from Kaggle, which tracks sunspots on a monthly basis from 1749 until 2018. Sunspots do have seasonal cycles approximately every 11 years. So let's try this out to see if we can predict from it. It's a CSV dataset with the first column being an index, the second being a date in the format year, month, day, and the third being the date of that month that the measurement was taken. It's an average monthly amount that should be at the end of that month. You can download it from Kaggle or if you're using the notebook in this lesson, I've conveniently hosted it for your on my Cloud Storage. It's a pretty simple dataset, but it does help us understand a little bit more about how to optimize our code to predict the dataset based on the nature of its underlying data. Of course, one size does not fit all particularly when it comes to data that has seasonality. So let's take a look at the code. Okay, first of all, if you're using a codelab, then you'll need to get the data into your codelab instance. This code will download the file that I've stored for you. You should really get it from Kaggle and store it on your own server or even manually upload it to codelab, but for convenience, I've stored it here. Here's the code to read the CSV file and get its data into a list of sunspots and timestamps. We'll start by importing the CSV library. Then we'll open the file. If you're using the codelab and the W get code that you saw earlier, downloads the CSV and puts it into slash temp. So this code just reads it out of there. This line, next reader, is called Before we loop through the rows and the reader, and it's simply reads the first line and we end up throwing it away. That's because the column titles are in the first line of the file as you can see here. Then, we will look through the reader reading the file line by line. Our sunspots are actually in column 2 and we want them to be converted into a float. As the file is read, every item will be read as a string so we may as well convert them now instead of iterating through the list later and then converting all the datatypes. Similarly, we'll read the time steps as integers. As much of the code we'll be using to process these deals with NumPy arrays, we may as well now convert a list to NumPy arrays. It's more efficient to do it this way, build-up your data in a throwaway list and then convert it to NumPy than I would have been to start with NumPy arrays, because every time you append an item to a NumPy, there's a lot of memory management going on to clone the list, maybe a lot of data that can get slow. If we plot our data it looks like this. Note that we have seasonality, but it's not very regular with some peaks and much higher than others. We also have quite a bit of noise, but there's no general trend. As before, let's split our series into a training and validation datasets. We'll split at time 1,000. We'll have a window size of 20, batch size of 32, and a shuffled buffer of 1,000. We'll use the same window dataset code that we've been using all week to turn a series into a dataset which we can train on.
---------------------------------------------------------------
За последние несколько недель вы работали с временными рядами и исследовали несколько методов для предсказывания их значений, включая статистический анализ, линейную регрессию и машинное обучение, включая как глубокие нейросети, так и рекуррентные нейронные сети. Но сейчас мы выйдем за пределы синтетических данных, воспользуемся настоящими данными из окружающего мира и применим то, что мы выучили, чтобы предсказать их. Давайте начнём с этого набора данных с Kaggle, где даётся ежемесячная сводка по числу пятен на Солнце, с 1749 по 2018 год. Солнечные пятна обладают цикличностью с периодом около 11 лет. Давайте посмотрим, что мы сможем для них предсказать. Этот набор данных находится в CSV-файле, где первая колонка — индекс, вторая — дата в формате год-месяц-день, а третья — данные за месяц, когда были проведены измерения. Это среднее число пятен, которое получилось к концу месяца. Вы можете скачать набор с Kaggle но если вы используете блокнот этого урока, то для вашего удобства я разместил набор в своём облачном хранилище. Это довольно простой набор данных, но он поможет нам немного лучше разобраться в том, как оптимизировать наш код, чтобы предсказывать значения ряда, основываясь на природе данных, которые он описывает. Конечно, не существует универсального подхода, особенно, когда дело доходит до данных с циклической компонентой. Итак, давайте посмотрим на код. Итак, во-первых, если вы используете colab, вам нужно будет затянуть данные в ваш colab. Этот код скачает файл, который я разместил для вас. По хорошему, вам нужно было бы скачать его с Kaggle и сохранить на своём сервере, или хотя бы загрузить вручную в colab, но для удобства я сохранил его тут. Этот код читает CSV-файл и загружает данные в списки для числа пятен и временных меток. Сперва импортируем библиотеку csv. Затем откроем файл. Если вы используете colab, то вызов wget, который вы только что видели, скачает файл и сохранит его в /tmp. Так что этот код просто читает его оттуда. Эта строка, next(reader), выполняется перед запуском цикла по всем строкам из reader, здесь просто считывается первая строка, которую мы отбрасываем. Это потому что в первой строке, как видите, находятся имена столбцов. Затем мы проходим циклом по строкам из reader, читая файл строка за строкой. Количество пятен лежат во втором столбце, и мы хотим преобразовать этот текст к числу с плавающей запятой. По мере чтения файла каждый его элемент считывается в виде строки, и можно преобразовать её в число сразу, а не считывать весь список целиком, лишь потом преобразовывая типы данных. Аналогично, мы считываем индексы как целые числа. Поскольку большая часть кода для обработки данных будет использовать массивы NumPy, можно сразу преобразовать наши списки в эти массивы. Так будет эффективнее собирать данные в одноразовый список, а затем преобразовывать его к NumPy-массиву — а не работать сразу с массивами NumPy, т.к. при каждом добавлении элемента в NumPy-массив происходит множество операций с памятью для клонирования списка, и при большом объёме данных работа может замедлиться. Если мы выведем данные на график, это будет выглядеть примерно так. Обратите внимание, что есть сезонность, но не очень строгая: некоторые максимумы намного выше, чем другие. Также данные довольно шумные, но общего тренда в них нет. Как и раньше, давайте разобьём наш ряд на обучающую и валидационную выборки. Мы разобьём их по временной отметке 1000. Размер окна зададим 20, размер пакета 32, а размер буфера для перемешивания — 1000. Мы используем тот же самый код windowe_dataset, который использовали всю неделю для преобразования рядов в наборы данных, на которых мы можем проводить обучение.

9(w4)-vide7: Train and tune the model (18.MLg_4c)

We'll go back to the simple DNN that we saw way back in week two for training on and we'll see what happens. We get a chart like this, which at least to the eyeball looks really good, but it has a very large MAE so something must be wrong. Indeed, if we zoom into the results we can see in a little bit more detail about how the forecast behaves in the original data. Our clue to the problem could be our window size. Remember earlier we said it's a 20 so our training window sizes are 20 time slices worth of data. And given that each time slice is a month in real time our window is a little under two years. But if you remember this chart, we can see that the seasonality of sunspots is far greater than two years. It's closer to 11 years. And actually some science tells us that it might even be 22 years with different cycles interleaguing with each other. So what would happen if we retrain with a window size of 132, which is 11 years worth of data as our window size. Now while this chart looks similar, we can see from the MAE that it actually got worse so increasing the window size didn't work. Why do you think that would be? Well, by looking back to the data, we can realize that it is seasonal to about 11 years, but we don't need a full season in our window. Zooming in on the data again, we'll see something like this where it's just the typical time series. Values later on are somewhat related to earlier ones, but that's a lot of noise. So maybe we don't need a huge window of time in order to train. Maybe we should go with something a little bit more like our initial 20, let's try 30. So if we look back at this code, we can change our window size to 30. But then look at the split time, the data set has around 3,500 items of data, but we're splitting it into training and validation. Now 1,000, which means only 1,000 for training and 2,500 for validation. That's a really bad split. There's not enough training data. So let's make it 3,000 and 500 instead. And then when we retrain, we'll get this. Our MAE has improved to 15 but can we make it even better? Well, one thing we can try is to edit the neural network design and height of parameters. If you remember, we had three layers of 10, 10, and 1 neurons. Our input shape is now larger at 30. So maybe try different values here, like 30, 15, and 1, and retrain. So let's switch back to 10, 10, 1 and instead look at the learning rate. Let's tweak it a little. Now after retraining, I can see my MAE has decreased a bit which is good.
---------------------------------------------------------------
Давайте вернёмся к простой глубокой нейросети, с которой мы работали на второй неделе, обучим её и посмотрим, что будет. Мы получим график вроде этого, который на глаз выглядит очень хорошо, но абсолютная ошибка очень высока, а значит, что-то здесь не так. И правда: если увеличить график, мы сможем рассмотреть подробнее, как прогноз ведёт себя по сравнению с исходными данными. Ключом к нашей проблеме может быть размер окна. Помните, раньше мы говорили, что он равен 20, так что в наше тренировочное окно помещается 20 временных отсчётов. И учитывая, что каждый отсчёт равен месяцу в реальном времени, ширина нашего окна получается немногим меньше двух лет. Но если вы вспомните этот график, то по нему видно, что периоды солнечной активности — куда дольше двух лет. Они близки к 11 годам. Некоторые учёные даже говорит, что период может составлять 22 года, где чередуются два различных цикла. Так что же произойдёт, если мы обучим сеть заново с размером окна 132, что соответствует 11 годам? Хотя новый график выглядит похоже, по абсолютной ошибке можно заключить, что стало только хуже, так что увеличение размера окна не сработало. Как думаете, почему? Ну, оглядываясь на данные, мы понимаем, что хотя их периодичность около 11 лет, но нам не надо, чтобы в окно помещался полный цикл. Увеличивая данные опять, мы видим что-то вроде этого, — довольно типично для временного ряда. Более поздние данные как-то зависят от предыдущих, но ещё здесь много шума. Так что возможно, при обучении нам не нужны огромные окна. Возможно, стоит попробовать окно лишь чуть больше, чем наши исходные 20 — давайте попробуем 30. Вернувшись к коду, мы можем заменить window_size на 30. Но давайте ещё посмотрим на split_time: в нашем ряду около 3500 элементов, но мы разделили его на обучающую и валидационную выборки по отметке 1000, что даёт лишь 1000 значений для обучения, и 2500 — для валидации. Это очень плохая разбивка. Нам не хватает данных для обучения. Давайте теперь отделим первые 3500. И когда мы обучим заново, то получим вот что. Наша ошибка улучшилась до 15, но можем ли мы ещё её улучшить? Среди прочего, можно попробовать изменить дизайн нейросети и гиперпараметры. Если вы помните, у нас было три слоя: по 10, 10 и 1 нейрону. Размер входа теперь больше, и составляет 30. Давайте попробуем другие значения, например, 30, 15 и 1, — и обучим заново. К удивлению, мы сделали небольшой шаг назад — абсолютная ошибка выросла. К тому же, дополнительные траты времени на лишние нейроны в слоях — не стоили того. Так что давайте вернёмся к 10, 10, 1, и попробуем поработать с темпом обучения. Немного подстроим его. Теперь, обучив повторно, я вижу, что ошибка чуть-чуть уменьшилась, и это хорошо.

10(w4)-vide8: Prediction (18.MLg_4c)

Out of interest, let's do a prediction. The window size I'm using is 30 steps, and the dataset is 3,235 steps long. So if I want to predict the next value after the end of my dataset, I would use this code. And I would get the result 7.0773993. The dataset goes up to July 2018, so I'm actually predicting 7.077 sunspots for August 2018. And if I look at this chart of observations, which does have some slightly different data from my dataset, I can see that the actual recorded number of sunspots in August 2018 was 8.7. So the prediction isn't too bad, but let's see if we can improve on it. With these settings, I got the MAE down to 13.75, and the prediction was 8.13, which is much closer to the actual real reading of 8.7. There is a random elements in creating models, however, so your results may vary. Doing accuracy based on a single prediction like this is also a recipe for disappointment, and you're much better off evaluating mean accuracy over a number of readings. So here, we looked at using a DNN to predict sunspot values. With a little bit of tuning, we reduced our MAE a bit. And when we tried to predict the next month's value using this model, we got quite close to the actual value. In the next video, you'll go through this workbook to see it in action. And then you should try it out for yourself, to see if you can improve on what I got. After that, you'll look into the RNNs again and see if you can get better predictions using those.
---------------------------------------------------------------
Ради интереса, давайте сделаем прогноз. Я использую размер окна в 30 шагов, а ряд имеет длину 3235 шагов. Так что если я хочу предсказать значение, сразу следующее за моим набором данных, то мне нужно использовать такой код. И он выдаёт прогноз 7.0773993. Набор данных был по июль 2018 г., так что я, по сути, предсказал 7.077 пятен на Солнце в августе 2018. И заглянув в эту таблицу наблюдений, где цифры слегка отличаются от моего набора данных, я вижу, что на самом деле в августе 2018 года отмечалось, в среднем, 8.7 пятен на Солнце. Так что прогноз не так уж и плох. Посмотрим, удастся ли его улучшить. С этими настройками абсолютная ошибка снизилась до 13.75, а предсказание получилось 8.13, что намного ближе к настоящему значению 8.7. Но в создании моделей есть элемент случайности, так что ваши результаты могут отличаться. Также вычисление точности на основе единичного прогноза, как здесь — это путь к разочарованию, так что лучше оценивать среднюю точность для множества показаний. Итак, мы рассмотрели использование глубокой нейросети для прогнозирования количества солнечных пятен. С помощью небольшой подстройки мы слегка уменьшили абсолютную ошибку. А когда мы попытались предсказать значение в следующем месяце, используя эту модель, мы подошли довольно близко к настоящему значению. В следующем видео мы разберём весь этот блокнот, и вы посмотрите его в действии. А затем поработайте с ним самостоятельно, чтобы увидеть, получится ли у вас улучшить мой результат. После этого вы ещё раз вернётесь к РНС и посмотрите, получится ли улучшить предсказания с их помощью.

11(w4)-Sunspots notebooks (Lab 2 & Lab 3): (18.MLg_4c)

The next screencasts will show how you can use different network architectures to predict real world data.
Here is the notebook for DNN only.
C4_W4_Lab_2_Sunspots_DNN.ipynb
Ungraded Lab: Predicting Sunspots with Neural Networks (DNN only)
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W4/ungraded_labs/C4_W4_Lab_2_Sunspots_DNN.ipynb
Here is the version with the combined layers.
C4_W4_Lab_3_Sunspots_CNN_RNN_DNN.ipynb
Ungraded Lab: Predicting Sunspots with Neural Networks
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W4/ungraded_labs/C4_W4_Lab_3_Sunspots_CNN_RNN_DNN.ipynb
---------------------------------------------------------------

12(w4)-vide9: Sunspots (18.MLg_4c)

In the previous lesson, you looked at using a real world data set, one with readings of sunspot activity over a couple of hundred years. And you saw how to build a simple DNN to predict activity using that data set. Now let's take a look at the notebook and we'll see it in action for ourselves. This code just imports numpy and pyplot and creates a helper function for plotting charts. This code downloads the data set and puts it into the temp directory. It's a very small data set so it should run very quickly. We'll now import the data from the CSV and create numpy arrays from it. We can plot the data to see it seasonality and its noise but there's no noticeable trend. We'll now split the data and setup our constants. Most notably the window size which I've set to 60. This code is a helper function for turning the data into a windowed data set. And now we'll train with a three layer DNN having 20, 10, and 1 neurons. We'll use stochastic gradient descent as our optimizer When the training is done, we can get forecasts across the validation set. And our plot looks pretty good. If we measured the MAE, we're at about 15. You should get slightly different values due to the randomness of the model initialization and stochastic gradient descent. So don't worry if it's a little off. If it is way off, then go back and check your code or restart the runtime and try again.
---------------------------------------------------------------
В предыдущем уроке вы учились работать с набором реальных данных на примере журнала солнечной активности за пару сотен лет. И вы видели, как строить простую DNN для предсказания активности по этим данным. Давайте теперь просмотрим блокнот и увидим его в действии. Как всегда, давайте проверим, установлен ли у вас TensorFlow 2. Да, установлен, так что можно продолжать дальше. Этот код импортирует numpy и pyplot и создаёт вспомогательную функцию для построения графиков. Вот этот код скачивает набор данных и кладёт его во временную папку. Это очень маленький набор данных, так что код должен отработать быстро. Теперь считаем данные из файла и загрузим их в массивы NumPy. Можно вывести данные на график и увидеть в них периодичность и шум, но в них нет заметного тренда. Теперь разделим данные и настроим наши константы. Обратите внимание, что размер окна я установил равным 60. Этот код — вспомогательная функция для преобразования к оконному набору данных. А теперь обучим трёхслойную нейросеть со слоями из 20, 10 и 1 нейрона. В качестве оптимизатора мы используем стохастический градиентный спуск с темпом обучения, равным 1e-7. Когда обучение закончено, мы можем получить прогнозы для валидационной выборки. И наш график выглядит довольно неплохо. Если мы измерим абсолютную ошибку, она будет около 15. Вы можете получить слегка другие данные из-за случайной составляющей при инициализации модели и стохастическом градиентном спуске. Так что не беспокойтесь, если ваше значение немного отличается. Если оно отличается сильно — вернитесь и проверьте ваш код, или перезапустите среду и попробуйте ещё раз.

13(w4)-vide10: Combining our tools for analysis (18.MLg_4c)

So we've looked at the sunspot data using a standard DNN like way back at the beginning of this course. We've also been working a lot with RNNs and a little with convolutional neural networks. So what would happen if we put them all together to see if we can predict the sunspot activity? This is a difficult dataset because like we've seen already, while it's seasonal the period is really long, around 11 years, and it's not perfectly seasonable during that period. So let's take a look at using all the tools we have to see if we can build a decent prediction using machine learning. So here's the first piece of code we can try. I've gone a little crazy here, so let's break it down piece by piece. First of all I'm setting the batch size to 64 and the window size to 60. Then we'll start with a 1D convolution that we'll learn 32 filters. This will output to a couple of LSTMs with 32 cells each before feeding into a DNN similar to what we saw earlier, 30 neurons, then 10, and one. Finally, as our numbers are in the 1-400 range, there is a Lambda layer that multiplies out our X by 400. With the first test run to establish the best learning, rate we get this chart. This suggests the best learning rate for this network will be around 10 to the minus 5. So when I trained for 500 epochs with this setup, here's my results. It's pretty good with a nice low MAE. But when I look at my loss function during training, I can see that there's a lot of noise which tells me that I can certainly optimize it a bit, and as we saw from earlier videos, one of the best things to look at in these circumstances is the batch size. So I'll increase it to 256 and retrain. After 500 epochs, my predictions have improved a little which is a step in the right direction. But look at my training noise. Particularly towards the end of the training is really noisy but it's a very regular looking wave. This suggests that my larger batch size was good, but maybe a little off. It's not catastrophic because as you can see the fluctuations are really small but it would be very nice if we could regularize this loss a bit more, which then brings me to another thing to try. My training data has 3,000 data points in it. So why are things like my window size and batch size powers of two that aren't necessarily evenly divisible into 3,000? What would happen if I were to change my parameters to suit, and not just the window and batch size, how about changing the filters too? So what if I set that to 60, and the LSTMs to 60 instead of 32 or 64? My DNN already look good, so I won't change them. So after training this for 500 epochs, the noise and the loss function actually increased a bit, and that made me want to experiment with the batch size again. So I reduced it to just 100 and I got these results. Now here my MAE has actually gone up a little. The projections are doing much better in the higher peaks than earlier but the overall accuracy has gone down, and the loss has smoothed out except for a couple of large blips. Experimenting with hyperparameters like this is a great way to learn the ins and outs of machine learning, not just with sequences but with anything. I thoroughly recommend spending time on it and seeing if you can improve on this model. In addition, you should accompany that work with looking deeper into how all of these things in machine learning work and Andrew's courses are terrific for that. I strongly recommend them if you haven't done them already.
---------------------------------------------------------------
Итак, мы поработали с историей солнечной активности, применив стандартную многослойную нейросеть, как в самом начале нашего курса. Также мы много работали с РНС, и немного со свёрточными нейросетями. Что же будет, если сложить их все воедино, и посмотреть, сможем ли мы предсказать солнечную активность? Это непростой набор данных, потому что, как мы уже видели, хотя в них есть цикличность, но период очень длинный, около 11 лет, и цикличность проявляется не в полной мере на протяжении этого периода. Так что давайте посмотрим, как использовать все имеющиеся у нас инструменты, и проверим, сможем ли мы получить приличный прогноз при помощи машинного обучения. Итак, вот первый фрагмент кода, который мы попробуем. Я тут немного перемудрил, так что давайте разберём всё по частям. Прежде всего, я установил размер пакета, равный 64, а размер окна — 60. Далее я начал с одномерной свёртки, в которой обучаются 32 фильтра. Выход с неё поступает в пару LSTM, по 32 ячейки в каждой, перед тем, как попасть в нейросеть, подобную той, которую мы видели раньше: 30 нейронов, потом 10, потом 1. И наконец, т.к. наши числа лежат в диапазоне от 1 до 400, здесь добавлен лямбда-слой, умножающий выходное значение на 400. Сделав пробный запуск для определения оптимального темпа обучения, мы получаем такой график. Он подсказывает, что оптимальным темпом обучения для этой сети будет около 1e-5. И после обучения с этими настройками в течение 500 эпох я получил вот такие результаты. Они вполне хороши, абсолютная ошибка невелика. Но при взгляде на функцию потерь в процессе обучения я вижу в её значениях много шума, который говорит о том, что тут можно ещё немного оптимизировать. И как мы видели из предыдущих видео, одним из заслуживающих внимания параметров в подобных обстоятельствах является размер пакета. Так что я увеличу его до 256 и запущу обучение заново. После 500 эпох мои прогнозы немного улучшились, и это шаг в верном направлении. Но посмотрите на шум при обучении. Особенно под конец обучения — функция потерь здесь очень шумная, но это выглядит как периодическая волна. Это говорит о том, что увеличенный размер пакета — это хорошо, но, возможно, чересчур. Это не катастрофа, потому что, как видите, флуктуации очень малы, но было бы очень здорово, если бы нам удалось убрать и эти колебания, что заставляет меня попробовать кое-что ещё. В моей обучающей выборке 3000 элементов. Так почему у меня размер окна и размер пакета являются степенями двойки, которые вовсе не обязательно делят 3000 нацело? Что произойдёт, если я изменю параметры для достижения аккуратной разбивки? И речь не только о размере окна или пакета — как насчёт смены размеров фильтров? Что, если я изменю этот размер на 60? И количество ячеек в LSTM — тоже на 60, вместо 32 или 64? Набор полносвязных слоёв уже выглядит хорошо, так что его я менять не буду. Итак, после обучения этой сети в течение 500 эпох результаты снова улучшились, хотя и всего чуть-чуть. Это показывает, что мы движемся в верном направлении. Интересно, что шум и величина потерь — немного выросли, и это подталкивает меня ещё поэкспериментировать с размером пакетов. Так что я уменьшил его до 100, и получил такие результаты. Тут абсолютная ошибка немного увеличилась. Прогнозы на пиках стали куда лучше, чем раньше, но, в целом, точность упала, а график функции потерь стал более гладким, кроме пары крупных всплесков. Такие эксперименты с гиперпараметрами — отличный способ изучить все тонкости машинного обучения. Не только для временных рядов — а для чего угодно. Я абсолютно рекомендую тратить на это время, проверяя, можете ли вы улучшить модель. Кроме того, во время такой работы стоит глубже изучать, как работают все эти средства машинного обучения. И для этих целей великолепно подходят курсы Эндрю. Я настоятельно их вам рекомендую, если вы их ещё не прошли.

14(w4)- Week 4 Quiz: (18.MLg_4c)

1) How do you add a 1 dimensional convolution to your model for predicting time series data?:
1. Use a Conv1D layer type (+)
2. Use a ConvolutionD1 layer type
3. Use a 1Dconv Layer type
4. Use a 1DConvolution layer type
2) What's the input shape for a univariarte time series to a Conv1D:
1. []
2. [1]
3. [1, None]
4. [None, 1] (+)
3) You used sunspots dataset that was stored in CSV. What's the mane of the Python library used to read CSVs?:
1. PyFiles
2. PyCSV
3. CommaSeparatedValues
4. CSV (+)
4) If your CSV file has a header that you don't want to read into your dataset, what do you execute before iterating through the file using a 'reader' object?:
1. next(reader) (+)
2. reader.read(next)
3. reader.ignore_header()
4. reader.next
5) When you read a row from a reader and want to cast column 2 to another data type, for example, a float, what's the correct sintax?:
1. float(row[2]) (+)
2. Conver.toFloat(row[2])
3. You can't. It needs to be read into a buffer and a new float instantiated from the buffer
4. float f=row[2].read()
6) What was the sunspot seasonality?:
1. 11 years (-)
2. 22 years
3. 4 times a year
4. 11 or 22 year depending on who you ask (+)
7) After studying this course, what neural network type do you think is best for prediction time series like out sunspots dataset?:
1. Convolutions
2. DNN
3. RNN / LSTM ( - )
4. A combination of all other answers (+)
8) Why is MAE a good analytic for measuring accuracy of predictions for time series?:
1. It doesn't heavily punish larger errors like square errors do (+)
2. It punishes larger errors
3. It biases towards small errors
4. It only counts positive errors

15(w4)- Lecture Notes Week 4: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
hese slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------

16(w4)- Programming Assignment: Adding CNNs to improve forecasts: (18.MLg_4c)

Week 4: Using real world data
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/programming/0XyOq/adding-cnns-to-improve-forecasts/lab?path=%2Fnotebooks%2FC4W4_Assignment.ipynb

17(w4)- Wrap up: (18.MLg_4c)

Congratulations on getting this far! In this course, you've dipped your toe into the water of understanding sequences and some of the tools for predicting them! Hopefully, it was a fun journey and we're really looking forward to what you build next! :)
---------------------------------------------------------------
Поздравляем! В этом курсе вы погрузились в воду понимания последовательностей и некоторых инструментов для их предсказания! Надеюсь, это было веселое путешествие, и мы с нетерпением ждем того, что вы создадите дальше! :)

18(w4)-vide11: Congratulations! (18.MLg_4c)

So that brings you to the end of this course on sequences and prediction. I hope you've enjoyed looking at the myriad of different ways that you can use machine learning to make predictions based on sequential and time series data. That being said, you've really only scratched the surface of what's possible, and you've only just taken the first steps on your journey. There's lots more to learn, but with what you've achieved over the last few weeks, you're well-equipped to dive deeper and look at more complex scenarios, including things like multivariate time series data. We really hope you've enjoyed this course, and as always we'd love to hear your feedback as we create more. Thank you.
---------------------------------------------------------------
Итак, мы подошли к концу этого курса, посвящённого временным рядам и их прогнозированию. Надеюсь, вам понравилось изучать бесчисленное множество разных способов, которыми можно использовать машинное обучение для прогнозирования последовательностей и временных рядов. Вы, так сказать, лишь немного поскребли по поверхности возможного, и сделали лишь первые шаги в своём путешествии. Вам предстоит изучить ещё массу всего, но с тем, чего вы добились за истекшие несколько недель, вы уже подготовлены к более глубокому погружению, к работе с более сложными случаями, включая, например, многовариантные временные ряды. Очень надеюсь, что вы получили от курса удовольствие, и мы, как всегда, будем рады получить от вас отзывы, чтобы творить и дальше. Спасибо.

19(w4)-References: (18.MLg_4c)

This is a compilation of resources appearing in the lecture videos, ungraded labs, and assignments.
Week 1:
● Moore's Law (Wikipedia)
https://en.wikipedia.org/wiki/Moore%27s_law
● Spurious Correlations: Arcades vs Doctorates (Tyler Vigen)
https://tylervigen.com/view_correlation?id=97
● Birth and Death Rate in Japan (Wikipedia)
https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Bdrates_of_Japan_since_1950.svg/450px-Bdrates_of_Japan_since_1950.svg.png
● Global Temperature and Carbon Dioxide (GlobalChange.gov)
https://www.globalchange.gov/browse/multimedia/global-temperature-and-carbon-dioxide
● Slope-Intercept Form (Wikipedia)
https://en.wikipedia.org/wiki/Linear_equation#Slope–intercept_form_or_Gradient-intercept_form
● Tensorflow API (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf
● Numpy (Official Website)
https://numpy.org
● Pyplotv (Official Website)
https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.html
● Keras Metrics (Official Website)
https://www.tensorflow.org/api_docs/python/tf/keras/metrics/
---------------------------------------------------------------
Week 2:
● tf.data API (TF Documentation)
https://www.tensorflow.org/guide/data
● tf.data.Dataset (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/data/Dataset
● Flatten a dataset of windows (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/data/Dataset#flatten_a_dataset_of_windows_2
● LearningRateScheduler (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/LearningRateScheduler
---------------------------------------------------------------
Week 3:
● Huber Loss (Wikipedia)
https://en.wikipedia.org/wiki/Huber_loss
● SimpleRNN (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/layers/SimpleRNN
● Lambda Layer (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda
● Activation Functions (Wikipedia)
https://en.wikipedia.org/wiki/Activation_function#Table_of_activation_functions
● LSTM (DeepLearning.AI)
https://www.coursera.org/lecture/nlp-sequence-models/long-short-term-memory-lstm-KXoay
● LSTM Layer (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM
---------------------------------------------------------------
Week 4:
● Convolutional Neural Networks (DeepLearning.AI)
https://www.coursera.org/learn/convolutional-neural-networks
● Mini-batch Gradient Descent (DeepLearning.AI)
https://www.youtube.com/watch?v=4qJaSmvhxi8
● Sunspots Dataset (Robert Valt)
https://www.kaggle.com/datasets/robervalt/sunspots
● Solar Conditions (Australian Bureau of Meteorology)
https://sws.bom.gov.au/Solar/1/6
● Daily Minimum Temperatures in Melbourne (hosted by Jason Brownlee, source: Australian Bureau of Meteorology)
https://github.com/jbrownlee/Datasets/blob/master/daily-min-temperatures.csv

20(w4)-Acknowledgments: (18.MLg_4c)

In addition to the original Curriculum Developers, the following people made significant contributions to the Course 4 refresh:
Quiz Revisions:
Diego Peluffo
Engineering Support:
Andres Zarta
Testing and Mentorship:
Giovanni Lignarolo
Deepthi Locanindi
Chris Favila
Testers:
Xinyue Zhao
Álvaro Ramajo Ballester
Mayank Ghogale
Pawel Piela
Bartosz Pieniak
Nilosree Sengupta
Steve Sun
Davide Tisi
Marketing:
Ishita Chaudary
Video Production:
Diego Peluffo
Additional Administrative and Content Support:
Ryan Keenan
Inhae Koo
Lara Pheatt-Pitzer
Muhammad Mubashar
Christopher Moroney
Emma Afflerbach
Nikki Gibson
Finally, our sincerest thanks to YOU, for enrolling in this Specialization and becoming part of our global community of learners!

21(w4)-vide12: Specialization wrap up - A conversation with Andrew Ng (18.MLg_4c)

Congratulations on coming to the end of this TensorFlow and practice specialization. In the four courses, you learn how to build a deep neural network, how to build a conv net, how to build sequence models for NLP and finally, how to build time series models. You've built and you've learned a lot of stuff in the specialization, and I hope you give yourself a pat on the back for getting to the end. We've really come a long way, if you remember our very first lesson is we did two sets of numbers where the relationship was y equals 2x minus 1. We had a little DNN that people use then to learn that and to do that pattern matching of the x against y, but since then, we've gone into computer vision, natural language processing, time sequence modeling, sunspots, all that thing. So I really think that you've really just taken the first step though on a much bigger journey, there's so much more stuff to learn. One of the pieces of feedback that we get from students is that they really love this, but they want to learn more. I always recommend that the other specializations that Andrew has done that I've personally learned from as well. So if you really want to go into more depth into for example, how an LSTM works or how an RNN works, or how even a convolution works, there's some great material out there, and we've designed these materials to mesh with each other. So if you really want to learn in-depth, Andrew is the master, and if you want to learn how to then apply that to code and how to take that, and put it into practice, then this course and future courses that we're working on will be really all around that. So we hope to see you there. As Lawrence said, I hope this is just a part of your journey to become great at deep-learning. The deep learning specialization compliments this one, and so if you want to go into greater depth, you can check that out too. There's still more to learn. So Lawrence and I are still going to be continuing to build additional specializations to help you learn even more about TensorFlow. Looking forward to it. Working with Lawrence has been the highlight of these past few months and I look forward to building more courses together. To all of you that stuck with us throughout all this period, thank you for all the hard work you put into learning these things and keep watching the space, we'll have more things for you in the future. Thank you.
---------------------------------------------------------------
Поздравляю с окончанием специализации "TensorFlow на практике". В четырёх курсах вы научились строить глубокие нейросети, строить свёрточные сети, модели последовательностей для естественных языков, и, наконец, строить модели для временных рядов. Вы многое построили и многому научились на нашей специализации, и я надеюсь, вы одобрительно похлопали себя по спине за то, что дошли до конца. Мы действительно прошли долгий путь. Если помните, на первом уроке мы взяли два набора чисел, отношение между которыми было y=2x-1. У нас была небольшая полносвязная нейросеть, которую использовали для обучения и следования этому шаблону соответствия между x и y. Но с тех пор мы познакомились с компьютерным зрением, обработкой естественных языков, моделированием временных рядов, солнечной активностью, и т.п. И я считаю, что вы и правда сделали лишь первый шаг на очень большом пути: ещё столь многому вам предстоит научиться. И из отзывов студентов мы видим, что им всё это очень понравилось, но они хотят научиться большему. Я всегда рекомендую другие специализации, которые подготовил Эндрю, я и сам учился на них. Так что если вы действительно хотите углубиться в то, как, к примеру, работает LSTM, или как работают РНС, или даже как работает свёртка, — там есть великолепные материалы, и мы спроектировали эти материалы так, чтобы они перекликались друг с другом. Так что если вы и правда хотите более глубоких знаний, то Эндрю — ваш наставник, а если затем захотите научиться применять всё это в коде, как применять эти вещи на практике, — тогда данный курс — а также будущие курсы, над которыми мы работаем, — будут ждать вас. Так что мы надеемся вас там увидеть. Как уже сказал Лоуренс, я надеюсь, что это лишь часть вашего путешествия к тому, чтобы стать мастером в глубоком обучении. Специализация по глубокому обучению дополняет эту, и если вы хотите погрузиться в детали, то можете рассмотреть её в качестве варианта. Ещё столько всего предстоит изучить. Так что Лоуренс и я продолжаем готовить новые специализации, чтобы помочь вам узнать о TensorFlow ещё больше. С нетерпением жду этого. Работа с Лоренсом была лучшей частью последних месяцев, и мне не терпится поработать над новыми совместными курсами. А всех вас, кто оставался с нами на протяжении этого периода, я благодарю за все усилия, вложенные вами в изучение этих тем. Оставайтесь на связи, у нас ещё будут для вас новинки. Спасибо.

22(w4)-What next?: (18.MLg_4c)

Ready to deploy your models to the world? Learn how to go live with your models with the
TensorFlow: Data and Deployment Specialization.
https://www.coursera.org/specializations/tensorflow-data-and-deployment?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=TF1CourseItem
Looking to customize and build powerful real-world models for complex scenarios? Check out the
TensorFlow: Advanced Techniques Specialization.
https://www.coursera.org/specializations/tensorflow-advanced-techniques?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=TF1CourseItem

23(w4)-(Optional) Opportunity to Mentor Other Learners: (18.MLg_4c)

Our sincere thanks to you for enrolling in this specialization and becoming part of our global community of learners!
If you are passionate about volunteering and giving back to the community by guiding other learners to complete this specialization and/or testing other specializations published by Deeplearning.AI in Coursera, then sign up for the DeepLearning.AI Mentorship Program.
https://docs.google.com/forms/d/e/1FAIpQLScHp04An_g9UJq5fX_uOVGGAUh1mZttbE6hDePqR58SrWDIyQ/viewform
Someone from the DeepLearning.AI staff will reach out to you when positions suitable to your profile are available.
Note: It is not mandatory to sign up. It is a purely optional and voluntary service


mpublic


My publications (mpublic)

1. Методика прогнозування технічного стану вузлів ГТД в умовах експлуатації. :
Стаття (8)
Збірник наукових праць. – К.: Науковий центр повітряних сил збройних сил України, 2004. - №7. – с. 251–258.
Чоха Ю.М., Галицький С.П.
2. Дослідження впливу профілю лопаті несучого гвинта на аеродинамічні характеристики ротора автожиру. :
Тези доповіді (1)
ПОЛІТ-2005: V міжнародна науково-практична конференція молодих учених і студентів, 12-13 квітня 2005 р.: тези доп. – К. 2005.- С. 8.
Іщенко С.О., Галицький С.П.
3. Дослідження стійкості автожиру різних аеродинамічних компонованих систем. :
Тези доповіді (1)
ПОЛІТ-2005: V міжнародна науково-практична конференція молодих учених і студентів, 12-13 квітня 2005 р.: тези доп. – К. 2005.- С. 9.
Іщенко С.О., Галицький С.П.
4. Оптимізація геометричних характеристик профілю лопаті несучого гвинта автожиру.: (1, ukr) ::
Стаття (5)
Вісник Національного авіаційного університету. - 2005. - №4. – С. 55 – 49.
Іщенко С.О., Галицький С.П.
(Optimization of geometrical characteristics of a structure of the profile of the carrying airscrew of autogyro.)
The data research are devoted questions of geometry profile influence on aerodynamic characteristics of the carrying airscrew rotor of autogyro. The linear regression analysis is used for reception of a new profile structure which has essentially improved aerodynamic performances of the carrying airscrew of autogyro.
https://jrnl.nau.edu.ua/index.php/visnik/article/view/1247
DOI: https://doi.org/10.18372/2306-1472.26.1247
5. Дослідження динаміки роботи ротора автожиру. :
Тези доповіді (1)
ПОЛІТ-2006: VІ міжнародна науково-практична конференція молодих учених і студентів, 11-12 квітня 2006 р.: тези доп. – К. 2006.- С. 12.
Іщенко С.О.
6. Модель несучого гвинта, що знаходиться в стані авторотації, безпілотного літального апарату типу «автожир». :
Тези доповіді (1)
Актуальні проблеми розвитку авіаційної техніки
науково практична конференція, 19-20 червня 2008 р.: тези доп. – К. 2009. - С.31.
Іщенко С.О.
7. Модифікація аеродинамічних профілів для зменшення впливу нестаціонарності.: (2, ukr) ::
Стаття (5)
Вісник Національного авіаційного університету. - 2008. - №3. – С. 39 – 43.
Переверзєв А.М., Пашинський Т.Е.
(Modification of the aerodynamic profile to reduce the impact of non-stationary.)
The review of works on an unstationary flow on wing profiles which forms change of vortex structure flow and essentially changes its aerodynamic characteristics is considered. Updating of contours of a profile can be, criterion of reduction of an unstationary flow influence, and also lead to reduction of an unstationary flow influence on aerodynamic characteristics.
https://jrnl.nau.edu.ua/index.php/visnik/article/view/1587
DOI: https://doi.org/10.18372/2306-1472.36.1587

8. Экспериментальные исследования состояния пограничного слоя, возмущенного генератором вихрей.: (3, ukr) ::
Стаття (6)
Системи озброєння і військова техніка. - 2008. - №3. – С. 104 – 109.
Іщенко С.О., Аббас Фадиль Махмуд
(Experimental researches of the state of border-line layer, indignant at generator of whirlwinds
S.A. Ischenko, O.V. Bondar', Abbas Fadil' Makhmud)
The results of experimental researches of the state of boundary layer indignant at the diffuzornim generator of whirlwinds are resulted. Researches are conducted in the wind-channel of the UTAD-2-2 National aviation university, having a certificate on metrologicheskie descriptions of stream and mean of measuring, at the location of generator of whirlwinds on a flat plate. It is proved, that the law of distributing of pulsations of speed in a boundary layer differs from normal. It is shown, that the generator of whirlwinds changes the epyuru distributing of speed on the height of boundary layer.
https://www.hups.mil.gov.ua/periodic-app/article/1287/eng
9. П'ятикомпонентна тензометрична система вагових випробувань для аеродинамічної труби ТАД-2 НАУ. :
Тези доповіді (1)
ПОЛІТ-2009: ІХ міжнародна науково-практична конференція молодих учених і студентів, 8-10 квітня 2009 р.: тези доп. – К. 2009.- С. 5.
Смаковий Я.О.
10. Багатокомпонентна система вимірювання аеродинамічних навантажень.: (4, ukr) ::
Стаття (9)
Вісник Національного авіаційного університету. - 2009. - №2. – С. 8 – 16.
Іщенко С.О.
(Multi-system measurement of aerodynamic loads)
The basic features of projection and manufacture of multicomponent system of measurement of aerodynamic loads of beam type are observed. The previous estimation of metrology performances of the gained system is conducted.
https://jrnl.nau.edu.ua/index.php/visnik/article/view/1701
DOI: https://doi.org/10.18372/2306-1472.39.1701
11. Експериментальне обладнання для дослідження авторотуючого несучого гвинта. :
Тези доповіді (1)
ПОЛІТ-2010: Х міжнародна науково-практична конференція молодих учених і студентів, 7-9 квітня 2010 р.: тези доп. – К. 2010. – Т.І.- С. 317.
12. Пристрій для визначення поля індуктивних швидкостей несучого гвинта в аеродинамічній трубі.: (5, ukr) ::
Патент (3)
Пат. 52913 Україна, МПК G01M 9/00/ - №201004421; Заявл. 16.04.2010; Опубл. 10.09.2010, Бюл. №17. – 3 с.
Давидов О.Р.,Іщенко С.О.
(Attachment for the designation of the field of inductive slips of a bearing screw in a wind tunnel.)
An attachment for designating the field of inductive fasteners of a bearing screw in an aerodynamic tube, which can hold a bearing screw in itself, a holder with a winding nozzle, two linear hydraulic drives, a mechanism for linking with supports, a block of twisting, setting h of forced movement, moreover, the first linear hydraulic drive ensures vertical movement holders, and the other linear hydraulic drive, through the linkage mechanism, secures the wraparound movement of the holder in the area where the hydraulic drives are located, which is inspected by the fact that two sensors of the apex position are additionally introduced, the third linear hydraulic drive, which from one side, so the very same as the first hydraulic drive by the mechanism of connection, and the other side of the connection with the body of the aerodynamic tube, moreover, the control of all three by hydraulic actuators is behind the auxiliary control block, which is the first one and the other input of the connection with the outputs of the sensors in the apex position nya hydraulic drive, as well as between the linkage mechanism and the aerodynamic tube housing.
https://uapatents.com/3-52913-pristrijj-dlya-viznachennya-polya-induktivnikh-shvidkostejj-nesuchogo-gvinta-v-aerodinamichnijj-trubi.html
13. Комплексний підхід до оцінки нерівномірного розподілу поля індуктивних швидкостей по диску авторотуючого несучого гвинта. :
Тези доповіді (4)
АВІА-2011: X міжнародна науково-технічна конференція, 19-21 квітня 2011 р.– К. 2011. – Т.II. – С. 17.32-17.35.
14. Evaluation of the stability derivatives in a longitudinal, lateral and transverse motion of the unmanned aerial vehicle in the curvilinear flight with rotation. :
Тези доповіді (3)
“Авіація у XXI столітті” – “Безпека в авіації та космічні технології”: V Всесвітній конгр 25-27 вересня 2012 р. – К.2012. – Т.І. С. 1.3.38-1.3.40.
Плахотнюк Є.С.

15. Дослідження аеродинамічних характеристик профілю в аеродинамічній трубі Утад-2 НАУ при кутах атаки 0-360 град. :
Тези доповіді (4)
АВІА-2013: XІ міжнародна науково-технічна конференція, 21-23 травня 2013 р.– К. 2013. – Т.II. – С. 17.32-17.35.
16. Parametric analysis of longitudinal stability unmanned aerial vehicle.: (6, eng) ::
Стаття (7)
Proceedings of the National Aviation University. - 2013. - №3. – p. 22 – 28.
Ударцев Є.П., Плахотнюк Є.С.
(Udartsev, I., Bondar, A., & Plakhotniuk, I.)
We consider the aerodynamic characteristics of unmanned aircraft container type, which were obtained in a wind tunnel and refined amended by soot blowing elements propeller system and the influence of the earth's surface. The estimation of longitudinal static stability and its dependence on altitude, damping, coordinates of center of gravity, shoulder horizontal tail, wings rejection of mechanization. The variation of these parameters enables to optimize balancing system with minimal losses.
DOI: https://doi.org/10.18372/2306-1472.56.5411
http://jrnl.nau.edu.ua/index.php/visnik/article/view/5411
17. The experimental equipment for wind tunnel TAD - 2 NAU :
Тези доповіді (4)
“Авіація у XXI столітті” – “Безпека в авіації та космічні технології”: V Всесвітній конгр. 25-27 вересня 2014 р. – К.2014. – Т.І. С. 1.2.1-1.2.4.
Іщенко С.О.
18. Navigation range and duration of flight of unmanned aerial vehicle: (7, eng) ::
Стаття (10)
Proceedings of the National Aviation University. - 2014. - №3. – p. 33 – 42.
Ударцев Є.П., Плахотнюк Є.С.
(Udartsev, I., Bondar, A., & Plakhotniuk, I. )
The problem of calculation of navigation range and the flight duration, different from estimated technicalrange by the accounting of operational features in balancing, influence of atmospheric flight conditions and the specificfeatures influencing aerodynamic resistance of unmanned aerial vehicle is considered.
DOI: https://doi.org/10.18372/2306-1472.60.7562
https://jrnl.nau.edu.ua/index.php/visnik/article/view/7562

19. Пристрій для визначення поля індуктивних швидкостей несучого гвинта в аеродинамічній трубі: (8, ukr) ::
Патент (4)
Пат. 94188 Україна, МПК G01M 9/00/ - №2013 12116; Заявл. 16.10.2013; Опубл. 10.11.2014, Бюл. №21. – 7 с.
Давидов О.Р., Іщенко С.О.
(Attachment for the designation of the field of inductive slips of a bearing screw in a wind tunnel)
An attachment for designating the field of inductive fasteners of a load-bearing screw in an aerodynamic tube, which can be used to extend the load-bearing screw, a holder with a winding nozzle, three linear hydraulic drives, a mechanism for linking with supports, a block for turning by a drive, a task in impulsive movement, two sensors of the top position, and the first line hydraulic drive secures the vertical movement of the holder, another linear hydraulic drive through the linkage mechanism secures the wraparound movement of the holder in the area where the hydraulic drives are located, and the third linear hydraulic drive, which connects one on the other side, just like the first hydraulic drive with a linkage mechanism, and on the other side of the connection with the body of the aerodynamic tube, moreover, the control of all three by hydraulic drives is behind the auxiliary block of the control, which is connected by the first and the other input to the outputs of the sensors of the apex position, which are rotated between the mechanism linkage and first hydraulic drive, as well as between the mechanism of sound 'viscosity and the body of the aerodynamic tube, and the third input of the system with the command of the controlled displacement, which is controlled by the addition of the third sensor of the apex position, the electric drive of the wraparound ruhu, which at one end of the connection holder, and the other through the sensor of the apex position with vimiryuvalny nozzle, the output of which is connected to the fourth input of the keruvannya block by the drive, and one of the outputs of the kerubanny block by the drive is connected to the inlet of the keruvannya to the electric drive of the wrapping ruh.
https://uapatents.com/8-94188-pristrijj-dlya-viznachennya-polya-induktivnikh-shvidkostejj-nesuchogo-gvinta-v-aerodinamichnijj-trubi.html
20. Лопать несучого гвинта: (9, ukr) ::
Патент (4)
Пат. 98644 Україна, МПК B64C 27/72/ - №2014 04085; Заявл. 16.04.2014; Опубл. 12.05.2015, Бюл. №9. – 4 с.
Ударцев Є.П. Давидов О.Р.
(Propeller blade)
1. The blade of the main screw, which contains the crown part, the central part, the tip, while the inflow is made in the central part of the blade, which is distinguished by the fact that the inflow is sequentially arranged in a row on the front and rear edges of the blade.
2. The propeller blade according to item 1, which is characterized by the fact that the forming surfaces of the inflow have the same geometric profile parameters as those used for the central part of the blade.
https://uapatents.com/5-98644-lopat-nesuchogo-gvinta.html
21. Дослідження характеристик малогабаритного шестиствольного приймача повітряного тиску :
Тези доповіді (5)
АВІА-2017: XІІІ міжнародна науково-технічна конференція, 19-21 квітня 2017 р.– К. 2017. – С. 22.40-17.44.
Дегтярьов В.В.


G_Events


Video. (G_Events)

1.Introduction ML Bootcamp (06.07):
(https://www.youtube.com/watch?v=WvQtDs7WJII&t=2s)
1) Причини вивчати МЛ: персоналізоване навчання, розробка лікарських засобів, аналіз ринку і прогнозування, виявлення загроз кібербезпеки, чат боти, автоманизація.
2) Кар'єрний розвиток з ML - навичками: ML, Data Engineers, Automation Engineers, NLP Engineers, AI Experts, Research Scientist, Pre-sales ML Solution Engineer.
3) Можливості під час курсу ML Bootcamp: course for two months (backpack)
4) TensorFlow Certificate on Coursera: + google certification, vaucher from 15 september to 31 december.
5) Kaggle: start 21 August (first 50 peoples take mini backpack).
6) Як пройти ML Bootcamp з користю: work with webinar.
7) TensorFlow Developer Certification: need PyCharm.
8) Q & A: popular chatBot (may be first for ML)

2.Career consultation with Google (11.07):
(https://www.youtube.com/watch?v=1kMr_16zUqQ)
1) Про специфіку роботи в різних типах компаній: Startup "learning by doing", Corporate, Outsource/Outstaff - corporate, NGO - non-rank organizations.
2) Як покращити своє резюме та презентаці для потенційних роботодавців: структура рузюме (Contacts: email, phone, Linkedin, Github; Summary/ Skills; Work Experience; Honours / Awards, Education (on years)), Контент (кастомізація під вакансію(вимоги з вакансіЇ); стратегічний підхід до контенту, перерахуйте технічні та функціональні обовязки, досягнення та вплив), Формат (1 А4.pdf, поточний досвід, список досягнень, візуальний баланс), Присутність Linkedin, Github (https://www.canva.com, google doc)
3) Як проходять співбесіди в різних компаніях, включаючи технічні та поведінкові інтервю: рекрут, технічне інтервю, дом завдання, зустріч з командою, поведінкове інтервю.
4) Як вести перемовини щодо винагороди та інші важливі деталі: дослідження ринку, розуміння структури компенсації, перегляд зарплати, бенефіти та страховка, можливості росту, Counter offer завжди мотивує компаню запропонувати більше
5) Q & A: Linkedin, dou, djinni (aihouse.org.ua)

3.Q&A session_1 (13.07):
(https://www.youtube.com/watch?v=TKKIqLKtqUM)
1) Щоб досягнути максимуму: -зрозуміти логіку кожного кроку(щоб було все зрозуміло, чому так а не інак, + ChatCPT);
- закінчили лабораторну, відкриваємо чистий ноутбук і кодимо самостійно;
- перерви обов'яково
- систематизувати навчання (завдання на кожний день)
- Google Bard AI (чат бот АІ), періодично повторювати пройдений матеріал, моделі
2) малими частинами, але часто; читати англійською;

4.MLOps Best Practices, how to build a scalable & reliable ML System (18.07):
(https://www.youtube.com/watch?v=UmQQY09hyc0)
Jakob Porschmann
- One Decade of Learnings from scaling ML o BNs of Users
- Only a tiny percentage of ML models make it to prod..
But why?
- Companies aim to do advanced ML but are missing solid foundations: Skills & Tools; Meaningful Applications; Data Relevance % Quality
- ML algorithms are NOT the competitive advantage, but high quality data & solid ML pipelines.
- Let's discuss how to: 1)collect the right data in the right quality; 2)tackle ML engineering complexity; 3)design an ML platform for business value.:
1) Assuring data quality, always
Design your ingestion pipeline flexibly and growth oriented, Consider: ETL vs ELT (where to process); stateful vs. stateless processing (how to process); ingestion volume. frequency and elasticity (how much to process); flexibility in data schemes (what to process); modularity of producers and consumers (of/for whom to process)
Google Cloud Platform:
Reliable, scalable and automated ML training & serving
Design your training pipeline rapid experimentation & business impact: You will want to retrain your models; You will need to retrain your models; Complexity comes from ML Engineering, not so much modelling.
Design your serving architecture for scalability and availability: volume of incoming inference requests (how much to serve); inference latency meeds (how quickly to serve); model residency (where to serve); feature serving pipeline (what to serve)
- Measure for business value
Business impact is ultimately the only reason any ML model exists: Define your specific & measurable northstar; Measure model impact; Translate Northstar to ML product ROI
- So where start? Build a data-driven culture; Make coherent tooling choices; Assure top quality data; Experiment rapidly & measure relevance.
- Cloud AutoML: — набор продуктов для машинного обучения, которые позволяет разработчикам с ограниченным опытом работы в области машинного обучения использовать технологии обучения и создания нейронных сетей.

5.Potential of building with Large Language Models (25.07):
(https://www.youtube.com/watch?v=PkN9ROGd_FY)
Vaibhav Singh:
Language Model.
Why Large language Models (LLMs)?
Transformers.
How to make LLVs work?
Prompting in action.
Building with LLMs.
Q & A session.
A language model is a statistical method that predicts the next word in a sequence of words.
Prompting can help a large language model to perform usefully on seen and unseen tasks

6.Deep Learning: Fully Connected Neural Networks (01.08):
(https://www.youtube.com/watch?v=ENi5SaTbVVQ)
Varen Kohli
Artificial Intelligence: Feature Engineering; Training; Test and Validation (Lifecycle of AI model)
https://quickdraw.withgoogle.com
Linear & Non Linear Data
ReLU, SoftMax
Reducing Loss: we can take small steps in the negative gradient direction that minimizes loss; this optimization strategy is called Gradient Descent
Live use cases
TensorFlow - Neural Network Playground (site for play from course)

7.Q&A session_2 (03.08):
(https://www.youtube.com/watch?v=ulzjjd5laN0&t=1s)
Need reading new articles, every day

8.What Can You Build with Embeddings (15.08):
(https://www.youtube.com/watch?v=OWnyDBfriRw)
Ivan Cheung, Engineer Google
What are embeddings
Demo: Embeddings for retrieval
Embedding application architecture
Out of scope
How to train embeddings
Mathematics of embeddings
Q & A session
---------------------
Embeddings let us encode words, documents, images, etc. into numerical vectors
Embeddings are created be passing the word or document through an embedding model
Embeddings are a low-dimensionality representation of higher-dimensionality data that retains semantic information
Vertex AI Embeddings API + Matching Engine
https://ai-demos.dev/demos/matching-engine

"9.Q&A session_3 (17.08):
(https://www.youtube.com/watch?v=QBEV6kK4uEo)
Bohdan Knysh,
БПЛА + Neural network, автономні системи наведення
Поради:
math free brow math loud ??? (for Data Science)
ML (Andrej Karpathy) https://www.youtube.com/@AndrejKarpathy/featured
----------------------
https://www.youtube.com/@TwoMinutePapers/featured
TensorFlow or PyTorch
""Computer Vision: Algorithms and Applications"" от Richard Szelisk (2012)
+ Wikipedia, last publication book
CV must be sent to the company (every day)"

10. Kaggle-змагання: питання та правила (22.08):
(https://www.youtube.com/watch?v=C8y1-nxQpzI)
1) Що таке Kaggle - платформа для змагань DS, ML.(брати участь у змаганнях, знаходити та публікувати dataset, досліджувати та будувати моделі, працювати з іншими data scientista, ML інженерами, навчатися
2) Які переваги участі у змаганнях Kaggle - нові практичні навички, доповнення портфоліо, робота із визначеними дедлайнами, робота в команді, зворотній зв'язок від експертів, нетворкінг з іншими фахівцями, вигравати призи
3) Особистий досвід - швидкий перехід з розробки в сферу DS, виділяє резюме серед інших, дає досвід роботи з різними даними, тримає в курсі останніх трендів та сучасних підходів
4) Оцінка змагання - основна метрика: наскільки дообре модель може передбачити таргетовану змінну - точність, швидкість, легкість інтерпретації
5) Як відбуваються змагання Kagle -
6) Як взяти участь у змаганні у рамказ ML Bootcamp - 21.08 - 04.09, eng, log in Kaggle
7) Поради для успішної участі - правильно підбирайте змагання, спочатку гарно зрозумійте правила та метрики, уважно дослідіть дані, почніть з простого, продумайте коректній процес валідації, не бійтеся експериментувати, читайте та беріть участь в дискусіях, досліджуйте поередні рішуння та статті по темі, не здавайтесь занадто швидео
Сесія запитань та відповідей -

11. Q&A session_4 (24.08):
(https://www.youtube.com/watch?v=CRM5qf70O1k)
Galuh Sahid taking about Kaggle model, dataset and etc

12. Q&A session_5 (31.08):
(https://www.youtube.com/watch?v=vX--bw21Vzs)
Ігок Бірук
Чому датасет такий не якісний? Чи відкриють код в кого +0,95?
1. deeplearning.ai (Andrew Ng ML, DL)
2. fast.ai (practical deep learning for beginners)
3. http://cs231n.stanford.edu (Deep Learning for Computer Vision)
4. https://www.deeplearningbook.org (Deep Learning)
5. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow
6. Approaching (Almost) Any Machine Learning Problem, Abhishek Thakur
----------------------
13. How to prepare for certification TensorFlow (05.09):
(-)
----------------------
All events:
(https://rsvp.withgoogle.com/events/ml-bootcamp-ukraine/home)
----------------------
TensorFlow Developer Certificate:
(https://www.tensorflow.org/certificate)
( https://app.trueability.com/signin )


F1


Links: (F1)

https://www.youtube.com/@Deeplearningai/playlists
---------------------------------------------------------------
https://developers.google.com/machine-learning/foundational-courses
---------------------------------------------------------------
https://www.youtube.com/playlist?list=PLOU2XLYxmsILr3HQpqjLAUkIPa5EaZiui
---------------------------------------------------------------
https://rsvp.withgoogle.com/events/ml-bootcamp-ukraine/additionalcourses_f2b8cd
“COURSERA_CAREERS”: https://www.coursera.org/articles/job-search-guide-resources?utm_source=marketing&utm_medium=email&utm_campaign=37786&sfmc_id=176023098&sfmc_key=0038W00002CxLqxQAF
---------------------------------------------------------------
Big Interview: https://coursera.biginterview.com/register?utm_source=marketing
---------------------------------------------------------------
resumeworded: https://resumeworded.com/coursera?utm_source=marketing&utm_medium=email&utm_campaign=37786&sfmc_id=176023098&sfmc_key=0038W00002CxLqxQAF
password: COURSERA_2021
---------------------------------------------------------------
online translate, resume, virtual W11, linkedin, github
---------------------------------------------------------------
.- simple code model every week; all model for ML; download all datasets; publications; video events; add courses from rsvp.withgoogle.com…
---------------------------------------------------------------
https://docs.google.com/forms/d/e/1FAIpQLSdt9nMUQNqDrtcxqNm3ZCOtAGCrt6VxuF6sfQvCneg90AE1Mg/viewform
---------------------------------------------------------------
Best GPT AI
https://internetua.com/top-10-neiromerej-dlya-sprosxennya-vashoyi-roboti
...
123

=======

NEXT week_3 (16.MLg_2c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3) Transfer Learning (16.MLg_2c)

(Трансферное обучение)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 13 minutes
Self-study: 45 min
Graded tasks (Tasks to be assessed): 2

(w3) Content (16.MLg_2c)

1. Transfer learning (dowload and take not own learned model)
2. Dropout layers
x = layers.Dropout(0.2)(x) (del 20% layers)
- Applying Transfer Learning to Cats v Dogs (Lab 1) (transfer and dropput)
- Programming Assignment: Transfer Learning - Horses vs Humans

(w3) Introduction: (16.MLg_2c)

Building models for yourself is great, and can be very powerful. But, as you've seen, you can be limited by the data you have on hand. Not everybody has access to massive datasets or the compute power that's needed to train them effectively. Transfer learning can help solve this -- where people with models trained on large datasets train them, so that you can either use them directly, or, you can use the features that they have learned and apply them to your scenario. This is Transfer learning, and you'll look into that this week!
---------------------------------------------------------------
Создание моделей для себя — это здорово, и это может быть очень эффективно. Но, как вы видели, вы можете быть ограничены имеющимися у вас данными. Не у всех есть доступ к массивным наборам данных или вычислительной мощности, необходимой для их эффективного обучения. Трансферное обучение может помочь решить эту проблему, когда люди с моделями, обученными на больших наборах данных, обучают их, чтобы вы могли либо использовать их напрямую, либо использовать изученные ими функции и применить их к своему сценарию. Это трансферное обучение, и вы изучите его на этой неделе!

(w3) Learning Objectives: (16.MLg_2c)

● Master the keras layer type known as dropout to avoid overfitting.
● Achieve transfer of learning to code using the keras API.
● Create a model that implements the functional Keras API instead of the widely used Sequential model.
● Learn how to freeze layers of an existing model to successfully implement transfer learning.
● Learn the concept of transfer learning to use convolutions learned by another model from a larger model.
data set
---------------------------------------------------------------
● Освойте тип слоя keras, известный как выпадение, чтобы избежать переобучения.
● Добейтесь переноса обучения в код с помощью keras API.
● Создайте модель, которая реализует функциональный API Keras вместо широко используемой модели Sequential.
● Узнайте, как заморозить слои существующей модели, чтобы успешно внедрить трансферное обучение.
● Изучите концепцию трансферного обучения, чтобы использовать свертки, изученные другой моделью из более крупной модели.
набор данных

1(w3)-video1: A conversation with Andrew Ng (16.MLg_2c)

Welcome back. Transfer learning is one of the most important techniques of deep learning and TensorFlow lets you do that with just a handful of lines of codes. Rather than needing to train a neural network from scratch we can need a lot of data and take a long time to train, you can instead download maybe an open-source model that someone else has already trained on a huge dataset maybe for weeks and use those parameters as a starting point to then train your model just a little bit more on perhaps a smaller dataset that you have for a given task, so it is called transfer learning. Transfer learning, and I find it's really cool because we've been looking at convolutional neural networks up to this point, and when we're training with a convolutional neural network we're extracting features from an image and learning those features, learning the ones that match images. But when we download a large models something like an inception that has all of these features that have already been extracted off lots more images than we can use, I find that really exciting because as you mentioned researchers who built these wonderful models of lots of images have been able to share them and today we've been looking at convolutions and convolutional neural networks where from scratch we've been training something off of our data and off of our images to be able to extract features from these and learn them. But now these models that have been trained off with lots and lots of images over a lot of time might have spotted other features that weren't in our dataset and will help us to build better convolutional networks. Yes. There's so much stuff for neural networks to learn about the world. There are edges, corners, round shapes, curvy shapes, blobs and then there are things like eyes, circles, squares, wheels. There's so many things in the world that convolutional neural networks can pick up on but if you have only a 1,000 images or even 25,000 images may not be enough data for content to learn all those things. So by taking an inception network or some other network that someone else's has trained you can basically download all this knowledge into your neural network to give it a huge and much faster start. It's really exciting to be a part of that community where these things are being shared so that people who don't have access to machinery to be able to build massive models like this one, are able to derive the features from the people who have done so. I personally find that really inspirational. Yes. Many days I wake up really grateful to the whole AI community for the openness, so many breakthrough AI ideas are shared in papers on the Internet, on the open source code shared on the Internet, and I think this has been a large reason for the rapid advance of AI. I think to all the learners if you end up doing something consider sharing it on the Internet as well freely to contribute back to this open community that's making all of us go much faster. Definitely. Transfer learning is a technical embodiment that lets us use these ideas to accelerate the whole field. One of the cool things about transfer learning is that it's so simple to implement, in TensorFlow you download a model and then you say set these models as trainable and freeze or lock those other layers and then you just run. Yes. In the course what the students are going to be looking at is the inception model which is a beautiful image classification and classifies a 1,000 images it has been trained on. I think it's like over a million images and what you're going to do is you're going to take a look at one of the lower levels in that. You're going to lock all the way down to that. You're going to add a DNN a deep neural network underneath that, and then you're just going to retrain for those lower levels, and as a result using all of these, I like to call it standing on the shoulders of giants, you're going to be doing all that to be able to make the classifiers that you've been building in the course to date much more efficient and maybe even quicker to be able to reach higher levels of accuracy than if you're training it from scratch. So this week, you'll learn how to implement transfer learning and use it to get your models to not only train faster but also get higher accuracy. Please dive in.
---------------------------------------------------------------
С возвращением! Перенос обучения — это одна из самых важных методик глубокого обучения, и TensorFlow позволяет вам организовывать её всего в несколько строк кода. Вместо того, чтобы тренировать нейросеть с нуля, нуждаясь в большом количестве данных и времени на тренировку, — вы можете скачать модель, возможно, с открытым кодом, которую кто-то уже тренировал на огромном наборе данных, возможно, в течение нескольких недель, — и использовать её параметры как отправную точку, с которой начать тренировать вашу модель, лишь чуть-чуть, и, возможно, на меньшем наборе данных, который вы собрали для вашей задачи. Вот это и называется переносом обучения. Перенос обучения — и я считаю, это действительно круто, потому что мы до сих пор смотрели на свёрточные нейросети, и когда мы тренировали свёрточные нейросети, мы извлекали признаки из изображений, и обучали на эти признаки, изучали те из них, которые определяют изображения. Но когда мы загружаем большие модели такие, как Inception, то у них уже есть все эти признаки, которые уже извлечены из куда большего количества изображений, чем мы можем использовать, и я нахожу это поистине впечатляющим, потому что, как вы упомянули, исследователи, которые строят эти чудесные модели на большом количестве изображений, могут делиться ими, и теперь мы смотрим на эти свёртки и свёрточные нейросети, которые с нуля мы не смогли бы натренировать с нашими данными и нашими изображениями так, чтобы суметь при этом извлечь из них признаки, узнать их. Но сейчас эти модели, которые были натренированы на очень большом количестве изображений в течение огромного количества времени, — способны улавливать другие признаки, которых не было в нашем наборе данных, и они помогут нам построить лучшую свёрточную сеть. Да. Есть так много всего, что нейросети должны узнать об окружающем мире. Есть края, углы, круглые формы, изогнутые формы, пятна, а ещё есть такие вещи, как глаза, круги, квадраты, колёса. В мире столько всего, что свёрточные сети могли бы выучить, но если у вас есть только тысяча изображений, или даже 25 тысяч изображений, то может быть недостаточно данных для того, чтобы всему этому научиться. И взяв сеть Inception, или какую-нибудь другую сеть, которую натренировал кто-то другой, вы можете фактически загрузить все эти знания в вашу нейросеть, чтобы дать ей мощный и куда более быстрый старт. Я действительно впечатлён тем, что являюсь частью этого сообщества, в котором делятся такими вещами, так что люди, у которых нет доступа к суперкомпьютерам, чтобы построить такие колоссальные модели, как эта, теперь способны позаимствовать признаки у тех, кто это уже сделал. Лично я считаю это очень вдохновляющим. Да, много дней я просыпаюсь по-настоящему благодарным всему сообществу, изучающему ИИ, за его открытость, ведь так много прорывных идей в области ИИ распространялись в статьях в Интернете, в открытом коде, выложенном в Интернете, и я думаю, это послужило существенной причиной быстрого развития ИИ. И я думаю, что все наши ученики, если они в итоге сделают что-то важное, подумают о том, чтобы тоже выложить это в свободный доступ в Интернет, чтобы вернуть долг этому открытому сообществу, которое даёт всем нам возможность быстрее развиваться. Несомненно. Перенос обучения — это техническое воплощение, которое позволяет нам использовать эти идеи, чтобы ускорить развитие целой области знаний. Одна из замечательных вещей в переносе обучения – это то, что его очень просто внедрить, в TensorFlow вы просто скачиваете модель, а потом указываете в коде, что эту модель можно тренировать, и замораживаете некоторые слои, и затем просто запускаете на выполнение. Да, и в этом курсе, который студенты сейчас смотрят, есть модель Inception, прекрасный классификатор изображений, и она классифицирует тысячу изображений, тогда как натренирована была, полагаю, на более чем миллионе изображений, и вам предстоит сделать вот что: взглянуть в ней на один из самых нижних уровней. Вы заморозите всё, что до него. Вы добавите ГНС, глубокую нейросеть, под этим слоем, а затем вы просто ещё немного потренируете эти нижние уровни, и в результате используете это всё, мне нравится называть это "стоять на плечах гигантов", вы сделаете это всё, чтобы сделать классификатор, созданием которого вы уже занимались при прохождении этого курса, — намного более эффективным, и, возможно, ещё быстрее достичь высших уровней точности, чем если бы вы тренировали его с нуля. Итак, на этой неделе вы научитесь внедрять перенос обучения и использовать его, чтобы ваша модель не только быстрее обучалась, но и давала более высокую точность. Пожалуйста, погружайтесь в курс.

2(w3)-video2: Understanding transfer learning: the concepts (16.MLg_2c)

In the previous lessons, you looked at building a binary classifier that predicted cats versus dogs or horses versus humans. You also saw how overfitting can occur and explored some practices for avoiding it. The problem with these of course, is that the training data was very small, and there's only so many common features that can be extracted, even if we do some tricks like image augmentation. But in both these cases, you built the model from scratch. What if you could take an existing model that's trained on far more data, and use the features that that model learned? That's the concept of transfer learning, and we'll explore that in this lesson. So for example, if you visualize your model like this with a series of convolutional layers before dense layer leads your output layer, you feed your data into the top layer, the network learns the convolutions that identify the features in your data and all that. But consider somebody else's model, perhaps one that's far more sophisticated than yours, trained on a lot more data. They have convolutional layers and they're here intact with features that have already been learned. So you can lock them instead of retraining them on your data, and have those just extract the features from your data using the convolutions that they've already learned. Then you can take a model that has been trained on a very large datasets and use the convolutions that it learned when classifying its data. If you recall how convolutions are created and used to identify particular features, and the journey of a feature through the network, it makes sense to just use those, and then retrain the dense layers from that model with your data. Of course, well, it's typical that you might lock all the convolutions. You don't have to. You can choose to retrain some of the lower ones too because they may be too specialized for the images at hand. It takes some trial and error to discover the right combination. So let's take a well-trained state of the art model. There's one called Inception, which you can learn more about at his site. This has been pre-trained on a dataset from ImageNet, which has 1.4 million images in a 1000 different classes.
---------------------------------------------------------------
На предыдущих занятиях вы наблюдали за построением бинарного классификатора, определяющего что на изображении: кошка или собака, лошадь или человек. Вы также видели, как может возникать переобучение, и изучили некоторые методы противодействия ему. Основная проблема, конечно, была в очень малом размере тренировочного набора, и при этом так много общих признаков можно извлечь, даже если мы используем ряд приёмов, например, аугментацию. Но в обоих этих случаях вы строили модель с нуля. Что, если бы вы могли взять существующую модель, натренированную на намного большем количестве данных, — и использовать признаки, которым эта модель научилась? В этом ключевая идея переноса обучения, и мы рассмотрим его на этом уроке. Например, если вы изобразите свою модель, как здесь, с набором свёрточных слоёв, предшествующих полносвязному слою, который ведёт в выходной слой, где вы подаёте данные в верхний слой, и сеть обучает свёртки, которые находят признаки в ваших данных. Но посмотрите на чужую модель, возможно, намного более сложную, чем ваша, натренированную на намного большем количестве данных. У неё есть свёрточные слои, и они здесь определяют признаки, которые уже выучены. Так что вы можете заморозить их, вместо того, чтобы дообучать ещё и на ваших данных, — и использовать их только для извлечения признаков из ваших данных, используя свёртки, которые уже обучены. Тогда вы можете взять модель, которая натренирована на очень большом наборе данных, и использовать свёртки, которые она обучила, когда классифицировала эти данные. Если вы вспомните, как свёртки создаются и используются для извлечения признаков, и о том, как признаки передаются по сети, — то поймёте, что имеет смысл просто использовать их, и дообучать только плотные слои этой модели на ваших данных. Конечно, это только распространённый вариант — замораживать все свёртки, но вы вовсе не обязаны это делать. Вы можете решить дообучить также некоторые из нижних свёрток, потому что они могут быть слишком специфичны для применения на ваших изображениях. Потребуется ряд проб и ошибок, чтобы найти подходящий вариант. Итак, давайте возьмём качественно обученную современную модель. Например, вот эту, которая называется Inception, и о которой вы можете больше узнать на её сайте. Она уже натренирована на наборе данных ImageNet, в котором 1.4 миллиона изображений, разделённых на 1000 классов.

3(w3)-video3: Coding transfer learning from the inception model (16.MLg_2c)

So let's take a look at how we would achieve this in code. We'll start with the inputs. In particular, we'll be using the keras layers API, to pick at the layers, and to understand which ones we want to use, and which ones we want to retrain. A copy of the pretrained weights for the inception neural network is saved at this URL. Think of this as a snapshot of the model after being trained. It's the parameters that can then get loaded into the skeleton of the model, to turn it back into a trained model. So now if we want to use inception, it's fortunate that keras has the model definition built in. So you instantiate that with the desired input shape for your data, and specify that you don't want to use the built-in weights, but the snapshot that you've just downloaded. The inception V3 has a fully-connected layer at the top. So by setting include_top to false, you're specifying that you want to ignore this and get straight to the convolutions. Now that I have my pretrained model instantiated, I can iterate through its layers and lock them, saying that they're not going to be trainable with this code. You can then print a summary of your pretrained model with this code but be prepared, it's huge. There's no way I can fit it all in a slide, even if I use a two point font like this. This is probably less than 10 percent of the summary of the model. Try it in the notebook for yourself.
---------------------------------------------------------------
Итак, давайте посмотрим, как написать для этого код. Мы начнём с импорта библиотек. В частности, мы будем использовать интерфейс слоёв keras, чтобы выбирать слои, и понимать, какие мы хотим использовать, как они есть, а какие мы хотим дообучать. Копия предварительно натренированных весов для нейросети Inception хранится по этой ссылке. Считайте это моментальным снимком модели после того, как она была обучена. Это параметры, которые можно загрузить в скелет модели, чтобы превратить её в натренированную модель. Итак, если мы хотим использовать Inception, то, к счастью, в Keras есть встроенное определение этой модели. Так что вы создаёте экземпляр сети, задав желаемую форму для ваших данных, и указав, что вам нужны не встроенные веса, а снимок, который вы только что скачали. В Inception V3 на самом верху есть полносвязный слой, так что, установив параметр include_top=False, вы указываете, что хотите его игнорировать, и переходить прямо к свёрткам. И теперь, когда я создал свой экземпляр предварительно натренированной модели, я могу пройтись по всем слоям, и заморозить их, имея в виду, что не собираюсь тренировать их в этом коде. Затем вы можете вывести сводку об этой модели с помощью данного кода, но будьте готовы: она огромная. Я никак не могу уместить это в один слайд,так даже если буду использовать шрифт размером в 2 пункта, как здесь. И это, вероятно, менее 10% сводки об этой модели. Попробуйте это в блокноте самостоятельно.

4(w3)-Adding your DNN: (16.MLg_2c)

In the previous video you saw how to take the layers from an existing model, and make them so that they don't get retrained -- i.e. you freeze (or lock) the already learned convolutions into your model. Now, you'll need to add your own DNN at the bottom of these, which you can retrain to your data. In the next video, you'll see how to do that...
---------------------------------------------------------------
В предыдущем видео вы видели, как взять слои из существующей модели и сделать их такими, чтобы они не подвергались переобучению — то есть вы заморозили (или заблокировали) уже изученные свертки в своей модели. Теперь вам нужно добавить свой собственный DNN внизу, который вы можете переобучить своим данным. В следующем видео вы увидите, как это сделать...

5(w3)-video4: Coding your own model with transferred features (16.MLg_2c)

All of the layers have names, so you can look up the name of the last layer that you want to use. If you inspect the summary, you'll see that the bottom layers have convolved to 3 by 3. But I want to use something with a little more information. So I moved up the model description to find mixed7, which is the output of a lot of convolution that are 7 by 7. You don't have to use this layer and is fun to experiment with others. But with this code, I'm going to grab that layer from inception and take it to output.
So now we'll define our new model, taking the output from the inception model's mixed7 layer, which we had called last_ouput. This should look exactly like the dense models that you created way back at the start of this course. The code is a little different, but this is just a different way of using the layers API. You start by flattening the input, which just happens to be the output from inception. And then add a Dense hidden layer. And then your output layer which has just one neuron activated by a sigmoid to classify between two items. You can then create a model using the Model abstract class. And passing at the input and the layers definition that you've just created.
And then you compile it as before with an optimizer and a loss function and the metrics that you want to collect. I won't go into all the codes to download cats versus dogs again, it's in the workbook if you want to use it. But as before you're going to augment the images with the image generator. Then, as before, we can get our training data from the generator by flowing from the specified directory and going through all the augmentations. And now we can train as before with model.fit_generator. I'm going to run it for 100 epochs. What's interesting if you do this, is that you end up with another but a different overfitting situation. Here is the graph of the accuracy of training versus validation. As you can see, while it started out well, the validation is diverging away from the training in a really bad way. So, how do we fix this? We'll take a look at that in the next lesson.
---------------------------------------------------------------
У всех слоёв есть названия, так что вы можете посмотреть на название последнего слоя, который вы хотите использовать. Если вы изучите сводку о модели, то увидите, что нижний слой сворачивается до размера 3x3. Но я хочу использовать слой с бо́льшим количеством информации, так что я пролистал описание модели, чтобы найти слой с названием mixed7, который является выходом множества свёрток размером 7x7. Вы не обязаны использовать именно этот слой, и было бы забавно поэкспериментировать с другими. Но в этом коде я собираюсь взять именно этот слой модели Inception, и использовать его выход.
А теперь зададим новую модель, взяв вывод из слоя mixed7 модели Inception, который мы назвали last_output. Это должно выглядеть в точности как полносвязная модель, которую вы создали давным-давно, в начале этого курса. Код немного другой, но это просто другой способ использования API слоёв. Вы начинаете с того, что делаете одномерным вход, которым нам служит вывод из Inception. А затем добавляете полносвязный скрытый слой. А за ним — выходной слой, в котором есть лишь один нейрон, активируемый сигмоидой, для классификации на два класса. Затем вы создаёте модель, используя абстрактный класс Model, и передаёте ей вход и определение слоёв, которые вы только что создали.
Затем вы скомпилируете её, как и раньше, задав оптимизатор и функцию потерь, а также метрики, которые вы хотите собирать. Я не буду углубляться в весь код, который снова загружает "кошки или собаки", он есть в блокноте, если вам надо. Но, как и раньше, вам нужна аугментация с помощью генератора изображений. Затем, как и раньше, мы получим наши тренировочные данные из генератора, читая их из указанной папки и пропуская через все аугментации. А теперь, как и прежде, натренируем модель, использовав model.fit_generator. Я собираюсь тренировать её 100 эпох. Интересно, что если вы так сделаете, то снова окажетесь в ситуации переобучения, только уже другой. Вот график верных ответов на обучении и валидации. Вы видите, что всё начиналось хорошо, а затем валидация очень далеко ушла от обучения. Как мы можем это исправить? Мы узнаем это в следующем уроке.

6(w3)-Using dropout!: (16.MLg_2c)

Another useful tool to explore at this point is the Dropout.
The idea behind it is to remove a random number of neurons in your neural network. This works very well for two reasons: The first is that neighboring neurons often end up with similar weights, which can lead to overfitting, so dropping some out at random can remove this. The second is that often a neuron can over-weigh the input from a neuron in the previous layer, and can over specialize as a result. Thus, dropping out can break the neural network out of this potential bad habit!
Check out Andrew's terrific video explaining dropouts here:
https://www.youtube.com/watch?v=ARq74QuavAo
---------------------------------------------------------------
Еще один полезный инструмент для изучения на этом этапе — Dropout.
Идея заключается в том, чтобы удалить случайное количество нейронов в вашей нейронной сети. Это очень хорошо работает по двум причинам: во-первых, соседние нейроны часто имеют одинаковые веса, что может привести к переоснащению, поэтому случайное отбрасывание некоторых нейронов может устранить это. Во-вторых, часто нейрон может перевешивать входные данные от нейрона предыдущего слоя и в результате может чрезмерно специализироваться. Таким образом, отсев может сломать нейронную сеть от этой потенциально вредной привычки!
Посмотрите потрясающее видео Эндрю, объясняющее отсев, здесь:
https://www.youtube.com/watch?v=ARq74QuavAo

7(w3)-video5: Exploring dropouts (16.MLg_2c)

In the previous lesson, we saw how to do transfer learning. But when we retrain the inception classifier features for cats versus dogs, we ended up over-fitting again. We also had augmentation, but despite that, we still suffered from over-fitting. So let's discuss some ways that we can avoid that in this lesson. Now here's the accuracy of our training set versus our validation set over 100 epochs. It's not very healthy.
There's another layer take in Keras called a dropout. And the idea behind the dropout is that layers in a neural network can sometimes end up having similar weights and possible impact each other leading to over-fitting. With a big complex model like this, that's a risk. So if you can imagine the dense layers can look a little bit like this. By dropping some out, we make it look like this. And that has the effect of neighbors not affecting each other too much and potentially removing overfitting. So how do we achieve this in code? Well, here's our model definition from earlier. And here's where we add the dropout. The parameter is between 0 and 1 and it's the fraction of units to drop. In this case, we're dropping out 20% of our neurons. For comparison, here's the chart of training against accuracy from before the dropout was added. When you see validation diverging away from the training like this over time, it's actually a great candidate to try using a dropout. And here's the impact of the dropout. You can see that it's very significant. So lets take a look at this in the workbook.
---------------------------------------------------------------
В предыдущем уроке мы увидели, как делать перенос обучения. Но когда мы дообучали классификатор из Inception для "кошек или собак", мы опять пришли к переобучению. У нас была и аугментация, но несмотря на это, мы всё ещё страдаем от переобучения. Давайте в этом уроке обсудим несколько способов избавиться от него. Вот доля верных ответов на тренировочном и валидационном наборах данных на протяжении 100 эпох. Она не слишком хорошая.
В Keras есть ещё один слой, называемый слоем исключения/дропаута. И замысел, на котором он основан, состоит в том, что иногда слои в нейросетях могут иметь похожие веса и влиять друг на друга, что приводит к переобучению. В таких больших и сложных моделях, как эта, такое возможно. И если представить полносвязные слои, выглядящие примерно так, то частичным исключением мы можем привести их к такому виду. Это приводит к тому, что соседи влияют друг на друга не слишком сильно, что может устранить переобучение. Как же мы добьёмся этого в коде? Вот как мы определили модель ранее. И вот как мы добавляем дропаут. Параметр должен быть между 0 и 1, это доля элементов, которые надо отбросить. Здесь мы отбрасываем 20% наших нейронов. Для сравнения, вот график тренировочной и валидационной доли верных ответов до того, как мы добавили дропаут. Когда вы видите, что доля верных ответов на валидации со временем далеко уходит от тренировочной — значит, пора попробовать дропаут. И вот эффект от дропаута. Вы можете видеть, что он очень существенный. Давайте посмотрим всё это в блокноте.

8(w3)-Applying Transfer Learning to Cats v Dogs (Lab 1): (16.MLg_2c)

Now that we've explored transfer learning, and taken a look at regularization using dropout, let's step through the scenario for Cats vs Dogs in this
notebook next.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/ungraded_lab/C2_W3_Lab_1_transfer_learning.ipynb
For more on how to freeze/lock layers, you can explore the
documentation here.
https://www.tensorflow.org/tutorials/images/transfer_learning
---------------------------------------------------------------
Применение трансферного обучения к игре «Кошки против собак» (лабораторная работа 1)
Теперь, когда мы изучили переносное обучение и взглянули на регуляризацию с помощью отсева, давайте рассмотрим сценарий «Кошки против собак» в этом
тетрадь рядом.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/ungraded_lab/C2_W3_Lab_1_transfer_learning.ipynb
Чтобы узнать больше о том, как заморозить/заблокировать слои, вы можете изучить
документация здесь.
https://www.tensorflow.org/tutorials/images/transfer_learning

9(w3)-video6: Exploring Transfer Learning with Inception (16.MLg_2c)

Here's the transfer learning workbook from this lesson. Let's step through it, and when we're done, you can try it for yourself. The first cell downloads the weights for a pre-trained inception network, and then instantiates a new instance of it using those weights. We will pull one of the convolutional layers as our input layer, and then take its output. We call this last output. Now, we'll set up our model taking the last output as the input to it. That'll be flattened, and then there'll be a dense layer, a dropout, and an output layer. The next cell will download the abbreviated version of cats versus dogs, unzip it into training and validation directories, and then set up the image generators. The training one will use augmentation as we've explored before. We can then see that the images are being loaded and segregated into classes correctly, 2,000 for training, 1,000 for validation. We'll now start the training. I'm only going to do 20 epochs. Keep an eye on the accuracy and validation accuracy metrics. I'm speeding up the video to save a little time. But as you can see, the training accuracy is steadily increasing, and the validation accuracy is settling in about the mid 90's. By the time we're done, the training accuracy is around 90 percent, and the validation is close to 97 percent. That's in pretty good shape. So let's plot the 20 epochs and we can see that the curves are in sync. This is a good sign that we're avoiding overfitting. So that's it for this lesson. In this and in the last few lessons, we spent a lot of time looking at convolutional neural networks for classifying binary values. Of course another scenario happens when you have to classify multiple objects. So in the next lesson, we'll look at what you have to do to achieve that.
---------------------------------------------------------------
Вот блокнот данного урока по переносу обучения. Давайте пройдёмся по нему, и когда мы закончим, вы сможете попробовать всё сами. Первая ячейка скачивает веса для предобученной сети Inception, а затем создаёт новый экземпляр сети, используя эти веса. Мы указываем на один из свёрточных слоёв как на наш входной слой, а затем берём его вывод. Мы называем его last_output. Теперь настраиваем нашу модель, взяв last_output в качестве входа для неё. Его надо сделать плоским, а затем добавить полносвязный слой, дропаут и выходной слой. Следующая ячейка скачает сокращённую версию набора "кошка или собака", распакует его в тренировочную и валидационную папки, и затем настроит генераторы изображений. Тренировочный генератор будет использовать аугментацию, как мы уже посмотрели. Мы видим, что изображения загружаются и делятся на классы правильно. 2000 на тренировку, 1000 на валидацию. Теперь начнём тренировку. Я запускаю её лишь на 20 эпох. Следите за тренировочной и валидационной долей верных ответов. Я ускоряю видео, чтобы сэкономить немного времени. Но как вы видите, тренировочная доля верных ответов постоянно увеличивается, а валидационная — колеблется около 95%. К тому времени, как мы закончим, тренировочная доля верных ответов будет около 90%, а валидационная — близка к 97%. Это довольно хорошо. Давайте выведем график за 20 эпох, и увидим, что кривые синхронны. Это хороший признак того, что мы преодолели переобучение. Вот и всё на этот раз. В этом и нескольких предыдущих уроках мы потратили много времени, рассматривая свёрточные нейросети для бинарной классификации. Конечно, вы встретитесь с другими особенностями, когда будете классифицировать на несколько классов. И в следующем уроке мы посмотрим, что вам для этого нужно сделать.

10(w3)-What have we seen so far?: (16.MLg_2c)

This week you've learned a lot of great new concepts!
You saw Transfer Learning, and how you can take an existing model, freeze many of its layers to prevent them being retrained, and effectively 'remember' the convolutions it was trained on to fit images.
You then added your own DNN underneath this so that you could retrain on your images using the convolutions from the other model.
You learned about regularization using dropout to make your network more efficient in preventing over-specialization and thus overfitting.
Before you get to the exercise for this week, let's have a quick quiz!
---------------------------------------------------------------
На этой неделе вы узнали много новых отличных концепций!
Вы видели Transfer Learning и то, как вы можете взять существующую модель, заморозить многие из ее слоев, чтобы предотвратить их переобучение, и эффективно «запомнить» свертки, на которых она была обучена, чтобы соответствовать изображениям.
Затем вы добавили свою собственную DNN под этим, чтобы вы могли переобучить свои изображения, используя свертки из другой модели.
Вы узнали о регуляризации с помощью отсева, чтобы сделать вашу сеть более эффективной в предотвращении чрезмерной специализации и, следовательно, переобучения.
Прежде чем вы приступите к упражнению на этой неделе, давайте проведем небольшую викторину!

11(w3)- Week 3 Quiz: (16.MLg_2c)

1)If I put a dropout parameter of 0.2, how many nodes will I lose?:
1. 20% of them (+)
2. 2% of them
3. 20% of untrained ones
4. 2% of untrained ones
2) Why is transfer learning useful?:
1. Because I can use all of the data from the original training set
2. Because I can use all of the data from the original validation set
3. Because I can use the features that were learned from large datasets that I may not have access to(+ -)
4. Because I can use the validation metadata from large datasets that I may not have access to
3) How did you lock or freeze a layer from retrainig?:
1. tf.freeze(layer)
2. tf.layer.frozen = true
3. tf.layer.locket =true
4. layer.trainable = false (+)
4) How do you change the number of classes the model can classify when using transfer learning?(i.e. the original model handled 1000 classes, but yours handles just 2):
1. Ignore all the classes above yours (i.e. Numbers 2 onwards if I'm just classing2)
2. Use all classes but set their weights to 0
3. When you add your DNN at the bottom of the network, you specify your output layer with the number of classes you want(+)
4. Use dropouts to eliminate the unwanted classes
5) Can you use Image Augmentation with Transfer Learning Models?:
1. No, because you are using pre-set features
2. Yes, because you are adding new layers at the bottom of the network, and you can use image augmentation when training these(+)
6) Why do dropouts help avoid overfitting?:
1. Because neighbor neurons can have similar weights, and this can skew the final training(+)
2. Having less neurons speeds up training
7) What would the symptom of a Dropout rate being set too nigh?:
1. The network would lose specialization to the effect that it would be inefficient of ineffective at learning, driving accuracy down (+)
2. Training time would increase due to the extra calculations being required for higher dropout
8) Which is the correct line of code for adding Dropout of 20% of neurons using TensorFlow:
1. tf.keras.layers.Dropout(20)
2. tf.keras.layers.DropoutNeuros(20)
3. tf.keras.layers.Dropout(0.2) (+)
4. tf.keras.layers.DropoutNeuros(0.2)

12(w3)-video7: Week 3 Wrap up (16.MLg_2c)

Congratulations, you've reached the end of week three. This week, hopefully you're excited as I was by some of the things that you learned. When you looked at Transfer Learning, just realize some of the things that were there, that were available for you, that you were able to take somebody else's model, a massive model that took a long time with a lot of data to train from, but you were able to build on that to make your models even better. I personally find that something that's really inspiring and something that really excites me. But next week we're going to switch gears a little bit, and we're going to take a look at moving from your binary classification to multi class classification to just round out your toolbox. I'll see you there.
---------------------------------------------------------------
Поздравляю, вы достигли конца третьей недели. На этой неделе, надеюсь, вы, как и я, восхитились тому, что узнали. Когда вы смотрели на перенос обучения, то одно только понимание того, что в него входит, что оно вам доступно, и можно взять чьи-то чужие модели, огромные модели, которые нужно было тренировать много времени на большом количестве данных, — но вы смогли положиться на них, чтобы сделать ваши модели ещё лучше. Лично я считаю это очень вдохновляющим и восхитительным. Но на следующей неделе мы собираемся немного переключиться, и посмотрим, как перейти от вашей бинарной классификации — к мультиклассовой, чтобы пополнить ваш инструментарий. Увидимся.

13(w3)-Lecture Notes Week 3: (16.MLg_2c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice These slides are distributed under the Creative Commons License.DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
ou may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах Эти слайды распространяются по лицензии Creative Commons. DeepLearning.AI делает эти слайды доступными для образовательных целей.
https://www.deeplearning.ai
Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные подробности о лицензии см. на странице https://creativecommons.org/licenses/by-sa/2.0/legalcode.

14(w3)-Programming Assignment: Transfer Learning - Horses vs Humans: (16.MLg_2c)

This week your exercise will be to apply what you've learned about Transfer Learning to see if you can increase training accuracy for Horses v Humans. To avoid crazy overfitting, your validation set accuracy should be around 95% if you do it right!
Your training should automatically stop once it reaches this desired accuracy.
Let's now use Transfer Learning to increase the training accuracy for Horses v Humans!
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/assignment/C2W3_Assignment.ipynb
This notebook is hosted on github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
You should upload one file:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
train_val_generators
create_pre_trained_model
output_of_last_layer
create_final_model
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
На этой неделе вам предстоит применить то, что вы узнали о трансферном обучении, чтобы увидеть, сможете ли вы повысить точность обучения в игре «Лошади против людей». Чтобы избежать сумасшедшего переоснащения, точность вашего набора проверки должна быть около 95%, если вы все сделаете правильно!
Ваша тренировка должна автоматически остановиться, как только она достигнет желаемой точности.
Теперь давайте воспользуемся трансферным обучением, чтобы повысить точность обучения в игре «Лошади против людей»!
Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W3/assignment/C2W3_Assignment.ipynb
Этот блокнот размещен на github, поэтому для сохранения любых изменений вам необходимо создать его копию на вашем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».
Вы должны загрузить один файл:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
train_val_generators
create_pre_trained_model
output_of_last_layer
create_final_model
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

NEXT week_4 (16.MLg_2c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w4) Multiclass Classifications (16.MLg_2c)

(Мультиклассовые классификации)
(Convolutional Neural Networks in TensorFlow)
---------------------------------------------------------------
Video: 11 minutes
Self-study: 46 min
Graded tasks (Tasks to be assessed): 2

(w4) Content (16.MLg_2c)

1. Moving from binary to multi-class classification
2. Introducing the Rock-Paper-Scissors dataset
3. Train a classifier with Rock Paper Scissors
4. Test the Rock Paper Scissors classifier
- Check out the code! (Lab 1)

(w4) Introduction: (16.MLg_2c)

You've come a long way, Congratulations! One more thing to do before we move off of ConvNets to the next module, and that's to go beyond binary classification. Each of the examples you've done so far involved classifying one thing or another -- horse or human, cat or dog. When moving beyond binary into Categorical classification there are some coding considerations you need to take into account. You'll look at them this week!
---------------------------------------------------------------
Вы прошли долгий путь, поздравляю! Еще одна вещь, которую нужно сделать, прежде чем мы перейдем от ConvNets к следующему модулю, и это выйти за рамки бинарной классификации. Каждый из приведенных вами примеров включал классификацию того или иного объекта — лошадь или человек, кошка или собака. При переходе от бинарной к категориальной классификации необходимо учитывать некоторые аспекты кодирования. Вы посмотрите на них на этой неделе!

(w4) Learning Objectives: (16.MLg_2c)

● Build a multiclass classifier for the Sign Language MNIST dataset
● Learn how to properly set up the ImageDataGenerator parameters and the model definition functions for multiclass classification
● Understand the difference between using actual image files vs images encoded in other formats and how this changes the methods available when using ImageDataGenerator
● Code a helper function to parse a raw CSV file which contains the information of the pixel values for the images used
---------------------------------------------------------------
● Создайте многоклассовый классификатор для набора данных MNIST языка жестов.
● Узнайте, как правильно настроить параметры ImageDataGenerator и функции определения модели для многоклассовой классификации.
● Понимать разницу между использованием реальных файлов изображений и изображений, закодированных в других форматах, и понимать, как это меняет методы, доступные при использовании ImageDataGenerator.
● Создайте вспомогательную функцию для анализа необработанного CSV-файла, который содержит информацию о значениях пикселей для используемых изображений.

1(w4)-video1: A conversation with Andrew Ng (16.MLg_2c)

The last few you train horse versus humans, cats versus dogs, would bind the classification problems with just two output. For a lot of applications, you might want more than two output courses such as Rock Paper Scissors where you would have three possible courses. So in this week, you learn the details of how to implement this. And in fact, you've actually seen one version of this already in the first course where you did the ten course classification problem of fashion. But in this week, you'll learn the important coding difference of how to actually build these multi-class classifiers. >> Yes, exactly, and it's one of the things that's really exciting about the image data generator is how your images get automatically labeled based on the directories that they're in. So we'll take a look at having with rock, paper, scissors, for example, we'll have three sub-directories of rock, paper, and scissors with the images in them. And we'll learn how the image data generator then works in outside of binary mode and in multi-class mode. We'll also look at the coding changes that you would have within the DNN part of your convolutional neural network so that you can work more efficiently with multi-class. >> And one of the really cool things we'll see this week is the rock, paper, scissors data set that you generated using computer graphics. >> Yeah, so I wanted to explore that one of the bottlenecks I find in creating data sets is in getting access to data. And if I wanted to build a rock, paper, scissors, I wanted to have people of different races hands. So Asian hands, black hands, white hands. I wanted to have male and female hands. I wanted to have nail polish and pointy nails on some and I wanted to have big hands and little hands. And if I were to do that with real images, I'd have to hire a lot of models and I didn't have the budget for that. And so, I thought well, what if I do it with CGI? And if I generate CGI hands for all of these, and then to see. Because convolutions are really all about extracting features. What does a finger look like? What does a finger nail look like? That type of thing. And with photo real CGI, the convolutions that make for finger might look exactly the same that it would be of a photograph of a hand. So I wanted to explore that and do some training on that. And it works surprisingly well. >> Yeah, one of the exciting developments in deep learning is that computer graphics is advanced to the point where more and more groups are considering using computer graphics to generate images to feed to these incredibly data hungry deep learning algorithms. Several years ago, when computer graphics was less advanced, it was like a slightly fishy thing to do to use computer graphics to synthesize data. And even though today, using graphics, not a slam dunk, it does not always work, and there's still problems quite often. I thought it was really cool that you were able to generate a pretty decent data set, certainly good enough for a learning tool. And in other context, I see companies starting to explore these ideas for more and more settings as well. >> Yeah, I think as an industry, we're only getting started with it. And that's really, really good for us to experiment with these things. And hopefully, the students in this course being able to experiment using these CGI based data sets will be a nice introduction for them. >> Yeah, so more data to feed to this giant hungry maw of our data hungry deep learning algorithms. >> Exactly. >> So in this week, you get to play with this cool new data set and use it to practice implementing building multi-class classifiers in TensorFlow. Please dive in.
---------------------------------------------------------------
Ваши последние модели — "лошадь или человек", "кошка или собака" — ограничивались только двумя вариантами ответа. Для многих других задач вам, вероятно, понадобится более двух вариантов, например, три варианта в игре "камень-ножницы-бумага". И на этой неделе вы подробно изучите, как это сделать. Фактически, вы уже видели один вариант, в первом курсе, где вы делали классификацию набора с изображениями одежды по 10 классам. Но на этой неделе вы научитесь важной отличительной черте в кодировании того, как на самом строятся многоклассовые классификаторы. >> Да, точно. И одна из вещей, которая действительно восхищает в генераторах изображений, это то, что ваши изображения размечаются автоматически, в зависимости от того, в какой папке лежат. Давайте для примера посмотрим, что у нас получится с "камень-ножницы-бумага", у нас будут три подкаталога: для камня, ножниц и бумаги, с изображениями в них. И мы узнаем, как работает генератор изображений в режиме мультиклассовой, а не бинарной классификации. Мы также посмотрим на то, как меняется код в части, относящейся к устройству вашей свёрточной нейросети, чтобы можно было эффективнее работать с несколькими классами. И одна из действительно крутых вещей, которые мы увидим на этой неделе, — набор данных "камень-ножницы-бумага", который вы сгенерировали с помощью компьютерной графики. Да, я хотел изучить одно из узких мест, на которое наткнулся: получение доступа к данным. Если я хочу построить набор данных для "камень-ножницы-бумага", то мне нужны руки людей разных рас. Азиатские руки, чёрные руки, белые руки. Мне нужны мужские и женские руки. Мне нужны руки с маникюром, и несколько рук с длинными ногтями. Мне нужны большие руки и маленькие. И если бы я захотел работать на настоящих изображениях, мне пришлось бы нанять множество моделей. Но у меня не было на это денег. И, я подумал: а что, если я сделаю это при помощи компьютерной графики? И сгенерирую на компьютере руки со всеми этими параметрами, а там посмотрим? Потому что свёртки ведь извлекают все эти признаки: Как выглядят пальцы? Как выглядят ногти на пальцах? И тому подобные вещи. И с фотореалистичной графикой свёртка, тренируемая на поиск пальцев, должна выглядеть точно так же, как если бы это были фотографии рук. Итак, я захотел исследовать это, и пообучал на данном наборе. И это сработало на удивление хорошо. Да, одно из потрясающих событий в глубоком обучении — что компьютерная графика продвинулась настолько, что всё больше и больше групп рассматривает возможность её применения для генерации изображений, чтобы подавать их на вход всем этим невероятно голодным до данных алгоритмам глубокого обучения. Несколько лет назад, когда компьютерная графика была не такая развитая, использовать её для синтеза данных казалось несколько сомнительным делом. И даже сегодня её использование не гарантирует успеха, она не всегда работает, всё ещё часто бывают трудности. По-моему, это действительно круто, что вы смогли сгенерировать вполне пристойный набор данных, который явно достаточно хорош для обучения. И в другом контексте, я вижу, как компании всё больше используют эти идеи, применяя их всё шире и шире. Да, я думаю, индустрия только начала с этим разбираться. И для нас очень, очень полезно экспериментировать с такими вещами. И я надеюсь, студенты на этом курсе научатся экспериментировать с наборами данных, полученных с помощью графики, для них это будет хорошее введение. Да, чтобы ещё больше данных скормить ненасытной утробе наших жадных к данным алгоритмов глубокого обучения. Именно. Итак, на этой неделе вы поиграете с этим крутым новым набором данных, и примените его, чтобы попрактиковаться в построении мультиклассового классификатора в TensorFlow. Приглашаем вас приступать.

2(w4)-video2: Moving from binary to multi-class classification (16.MLg_2c)

In the last few lessons, you've been building a binary classifier. One which detects two different types of objects, horse or human, cat or dog, that type of thing. In this lesson, we'll take a look at how we can extend that for multiple classes. Remember when we were classifying horses or human, we had a file structure like this. There were subdirectories for each class, where in this case we only had two. The first thing that you'll need to do is replicate this for multiple classes like this. It's very similar and here you can see that both the training and validation have three subdirectories. One for Rock, one for Paper, and one for Scissors. In these, we can put training and validation images for Rock, Paper, and Scissors.
---------------------------------------------------------------
Последние несколько уроков вы строили бинарный классификатор. Который различает два разных типа объектов: лошади или люди, кошки или собаки, и тому подобное. В этом уроке мы посмотрим, как можно обобщить это на несколько классов. Вспомните, что когда мы классифицировали лошадей и людей, у нас была такая структура файлов. Были подкаталоги для каждого класса, и в этом случае их было только два. В первую очередь, вы должны воспроизвести это для нескольких классов, как вот здесь. Всё почти так же, и можно видеть, что и в тренировочном, и в валидационном каталоге есть по три подкаталога: один для "камня", один для "ножниц", и один для "бумаги". И в них мы можем положить тренировочные и валидационные изображения для камня, ножниц и бумаги.

3(w4)-Introducing the Rock-Paper-Scissors dataset: (16.MLg_2c)

Rock-Paper-Scissors is a dataset containing 2,892 images of diverse hands in Rock/Paper/Scissors poses. It is licensed CC By 2.0 and available for all purposes, but its intent is primarily for learning and research.
https://creativecommons.org/licenses/by/2.0/
Rock Paper Scissors contains images from a variety of different hands, from different races, ages, and genders, posed into Rock / Paper or Scissors and labeled as such. You can download the training set here, and the test set here.
These images have all been generated using CGI techniques as an experiment in determining if a CGI-based dataset can be used for classification against real images. I also generated a few images that you can use for predictions. You can find them here.
Note that all of this data is posed against a white background.
Each image is 300×300 pixels in 24-bit color
You'll see how this dataset can be used to build a multi-class classifier in the next video.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/supplement/HoOHN/introducing-the-rock-paper-scissors-dataset
---------------------------------------------------------------
«Камень-ножницы-бумага» — это набор данных, содержащий 2892 изображения разных рук в позах «камень/ножницы-бумага». Он имеет лицензию CC By 2.0 и доступен для всех целей, но предназначен в первую очередь для обучения и исследований.
https://creativecommons.org/licenses/by/2.0/
«Камень, ножницы, бумага» содержит изображения разных рук, представителей разных рас, возрастов и полов, помещенные в «Камень/ножницы, бумагу» и помеченные соответствующим образом. Вы можете скачать обучающий набор здесь, а тестовый набор здесь.
Все эти изображения были созданы с использованием методов CGI в качестве эксперимента по определению того, можно ли использовать набор данных на основе CGI для классификации реальных изображений. Я также создал несколько изображений, которые вы можете использовать для прогнозов. Вы можете найти их здесь.
Обратите внимание, что все эти данные расположены на белом фоне.
Каждое изображение имеет размер 300×300 пикселей в 24-битном цвете.
В следующем видео вы увидите, как этот набор данных можно использовать для создания многоклассового классификатора.

4(w4)-video3: Explore multi-class with Rock Paper Scissors dataset (16.MLg_2c)

Now, this is a new data set that I created for learning opportunities. It's freely available, and it consists of about 3,000 images. They've all been generated using CGI with a diverse array of models, male and female, and lots of different skin tones, and here's some examples. If you want to download the data sets, you can find them at this URL. It will contain a training set, a validation set, and some extra images that you can download to test the network for yourself. Once your directory is set up, you need to set up your image generator. Here's the code that you used earlier but, note the class mode was set to binary. For multiple classes, you'll have to change this to categorical like this. The next change comes in your model definition where you'll need to change the output layer. For a binary classifier, it was more efficient for you to just have one neuron and use a sigmoid function to activate it. This meant that it would output close to zero for one class and close to one for the other. Now, that doesn't fit for multi-class, so we need to change it, but it's pretty simple. Now, we have an output layer that has three neurons, one for each of the classes rock, paper, and scissors, and it's activated by softmax which turns all the values into probabilities that will sum up to one. So what does that really mean? Consider a hand like this one. It's most likely a paper, but because she has her first two fingers open, and the rest joined, it could also be mistaken as scissors. The output of a neural network with three neurons and a softmax would reflect that, and maybe look like this with a very low probability of rock, a really high one for paper, and a decent one for scissors. All three probabilities would still add up to one. The final change then comes when you compile your network. If you recall with the earlier examples, your loss function was binary cross entropy. Now, you'll change it's a categorical cross entropy like this. There are other categorical loss functions including sparse categorical, cross entropy that you used in the fashion example, and you can of course also use those. Around this for 100 epochs, and I got this chart, it shows the training hits a max at about 25 epochs. So I'd recommend just using not many, and that's all really that you have to do. So let's take a look at it in the workbook.
---------------------------------------------------------------
Итак, вот новый набор данных, который я создал для обучения. Он свободно доступен и состоит из порядка 3000 изображений. Все они сгенерированы с помощью компьютерной графики, с большим разнообразием моделей, мужских и женских, и множеством различных оттенков кожи, вот несколько примеров. Если вы хотите скачать этот набор данных, он находится по этой ссылке. Он содержит тренировочный набор, валидационный набор, и несколько дополнительных изображений, с помощью которых вы можете протестировать сеть. Когда вы задали путь к каталогу, вам надо настроить генератор изображений. Вот код, который вы использовали ранее, но обратите внимание, что class_mode был задан как 'binary'. Для нескольких классов вам нужно изменить его на 'categorical', как здесь. Следующие изменения вас ждут в определении модели, где вам нужно изменить выходной слой. Для бинарного классификатора было эффективнее использовать лишь один нейрон, активируемый сигмоидной функцией. Это значит, что он выдаёт число, близкое к 0, для первого класса, и близкое к 1 — для второго. Но это не годится для нескольких классов, поэтому нам надо изменить его, но это довольно просто. Теперь у нас будет выходной слой с тремя нейронами, по одному для каждого класса: камня, ножниц и бумаги, — и они активируются функцией softmax, которая для каждого класса выдаёт его вероятность, в сумме давая 1. Что же это значит на деле? Посмотрим на такую руку. Она больше похожа на бумагу, но из-за того, что первые два пальца разделены, а остальные сомкнуты, её можно ошибочно принять за ножницы. Вывод нейросети и тремя нейронами и софтмаксом покажет это, и может выглядеть примерно так, с очень низкой вероятностью для камня, высокой для бумаги и умеренной для ножниц. Все три вероятности в сумме дают единицу. И последнее изменение нужно внести, когда вы компилируете сеть. Вспомните, что раньше вашей функцией потерь была бинарная кросс-энтропия. Сейчас вам надо заменить её на категориальную кросс-энтропию, как здесь. Есть и другие категориальные функции потерь, включая разреженную категориальную кросс-энтропию, которую вы использовали в задаче с классификацией одежды, и вы, конечно, можете использовать здесь одну из них. Я запустил обучение на 100 эпох, и получил такой график, показывающий, что при обучении максимум достигается примерно за 25 эпох, так что я бы порекомендовал использовать их не так много. Вот и всё, что вам нужно сделать. Давайте посмотрим на всё это в блокноте.

5(w4)-Check out the code! (Lab 1): (16.MLg_2c)

Now that you've explored the data, and seen how the code can be modified from a binary class classifier to a multi class one, let's take a look at the notebook that implements that for us!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/ungraded_lab/C2_W4_Lab_1_multi_class_classifier.ipynb
---------------------------------------------------------------
Теперь, когда вы изучили данные и увидели, как можно изменить код с бинарного классификатора на многоклассовый, давайте взглянем на блокнот, который реализует это для нас!
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/ungraded_lab/C2_W4_Lab_1_multi_class_classifier.ipynb

6(w4)-video4: Train a classifier with Rock Paper Scissors (16.MLg_2c)

In the previous lesson, we looked at how you would go from the binary classifiers we'd been looking at throughout the course, to update it from multi-class classifier. In this video, we'll look at the Rock Paper Scissors workbook and explore how it perform multi-class classification. The first step is to get the data. There are two zip files, one for the training data, and one for the test set. Once we have the data, we'll unzip it into the subdirectories here.
Let's now take a look at some of the files within that. You can see there are 840 of each class and a few filenames. Let's now plot a few of the files so we can see what the data looks like. As we can see, we have a few different hands with different skin colors, and both male and female hands. Let's now build the model. Note that while the images are 300 by 300, we are setting up the image generators to give us 150 by 150 variance. It will resize them on the fly and augment the ones in the training directory. We'll also print out the model if you want to inspect it.
Now, the training begins. I'll speed up the video so that you can see the progress. Keep an eye on the accuracy and the validation accuracy. I'm only training for 25 epochs, based on the chart you saw in the last lesson. But by the time we reach the 10th epoch, we're already doing quite well.
By the time we finish, the training data is above 98% and the validation data is at 95 percent accuracy. This is highly specialized data that's optimized for this lesson and not a great real-world scenario for Rock, Paper, and Scissors. I'll discuss why in a moment but let's first plot the accuracy. We can see the training improving and trending towards one. The validation zig-zags a bit, but it's always between 0.9 and one after the first few epochs. Now, let's explore testing it with some images that it hasn't previously seen.
---------------------------------------------------------------
В предыдущем уроке мы посмотрели, как вы можете перейти от бинарного классификатора, которым мы занимались в течение всего курса, к новому для вас мультиклассовому классификатору. В этом видео мы посмотрим на блокнот для "камень-ножницы-бумага", и исследуем, как он справляется с мультиклассовой классификацией. Первый шаг — получить данные. Есть два zip-файла, один с тренировочным набором, и один с тестовым. Когда мы скачали данные, распакуем их каталог /tmp, тренировочные данные будут в /tmp/rps. Вы видите здесь подкаталоги. Давайте посмотрим несколько файлов оттуда. Вы видите, что к каждому классу относится по 840 файлов, вот несколько их имён. Давайте теперь выведем на экран изображения из нескольких файлов, чтобы посмотреть, на что эти данные похожи. Мы видим несколько разных рук с разным цветом кожи, как мужские, так и женские. Давайте построим модель. Обратите внимание, что хотя размер изображений 300x300, мы настраиваем генератор изображений так, чтобы он нам выдавал изображения размером 150x150. Он изменит их размер на лету и аугментирует изображения из тренировочного каталога. Выведем также сводку о модели, на случай, если вы захотите посмотреть на неё. Начинаем тренировку. Я ускорил видео, и вы можете следить за прогрессом. Смотрите на тренировочную и валидационную долю верных ответов. Я тренирую только 25 эпох, основываясь на графике из предыдущего урока. Когда мы достигаем 10-й эпохи модель уже довольно неплохая. Когда тренировка закончена, у нас доля верных ответов на тренировочном наборе свыше 98%, а на валидационном — около 95%. Дело в том, что это данные, специально подготовленные для этого урока, и не настолько хорошо подходящие под реальные сценарии игры в "камень-ножницы-бумагу". Я расскажу об этом немного позже, а сейчас давайте построим график верных ответов. Мы видимо, что на тренировочных данных показатель улучшается и стремится к единице. Доля верных ответов на валидационных данных немного скачет, но всегда находится между 0.9 и 1 после первых нескольких эпох. Теперь давайте протестируем модель на нескольких изображениях, которые она ещё не видела.

7(w4)-Try testing the classifier: (16.MLg_2c)

In the following video, you'll see Laurence testing the classifier. You should also try it out using the data that you can find here.
F:\Projekt\DOC\ML_Boodcamp\Video\2c_Convolutional Neural Networks in TensorFlow\ColabNotebook_files\week4\rps-test-set
---------------------------------------------------------------
В следующем видео вы увидите, как Лоуренс тестирует классификатор. Вы также должны попробовать это, используя данные, которые вы можете найти здесь.

8(w4)-video5: Test the Rock Paper Scissors classifier (16.MLg_2c)

I've generated a few that you can use to test, they're at the URL in the previous lesson with the training set, test set, and validation set are all link to. Download the RPS validation zip from the link shown and in it, you'll find 33 images of different hand models ones that weren't using the training and validation sets and they're in different poses. Let's now upload one of these to the workbook and we'll try and get what happens. I'm going to pick a paper pose, and the classification comes back as 1-0-0. When using the image generator, the classes come from directories and thus were sorted in alphabetical order. So the first value is for paper and then rock and then scissors. So we can see that this is correct. So if I try another one a scissors, we'll see that the third neuron lights up which is what I would expect. Lets now try a rock, and this one is a larger picture hence the high resin filename, and I want you to see how that would perform. It's slower to upload and it needs to re-scale, but we can see that it gets classified correctly as a rock. I can also upload all the files at once and see classifications for them all. So let's try that. I'm speeding up the video to get past all the uploads. So let's take a look at the classifications that I get back. Remember that the neurons are in the order paper then rock then scissors because it's alphabetical. So we can see that the first one is right. The third one is correct and the same with the fourth and the fifth. So let's keep looking through the list. They mostly seem to be correct. The rest of the data looks like it was classified correctly. So that was a look at multiclass classification. Hopefully, you found it interesting.
---------------------------------------------------------------
Я сгенерировал несколько изображений, которые можно использовать для теста. Они находятся по ссылке из предыдущего урока, там же, где и тренировочный набор, тестовый и валидационный наборы, — все вместе. Скачайте rps_validation.zip по указанной ссылке, и в нём вы найдёте 33 изображения различных рук, не использовавшихся в тестовом и валидационном наборах, и все руки в разных позициях. Давайте загрузим одно из них в блокнот, попробуем и посмотрим, что будет. Я выбираю позицию "бумага", и классификатор выдаёт результат 1-0-0. Когда мы используем генератор изображений, классы берутся из названий каталогов, и идут в алфавитном порядке, так что первое значение — это бумага, потом камень, а потом ножницы. Мы видим, что это так. Попробуем другой файл — "ножницы", мы увидим, что активирован третий нейрон, как мы и ожидали. Давайте попробуем "камень", и это одно из больших изображений, поэтому в его имени есть "hires". И я хочу, чтобы вы увидели, как работает на нём. Оно медленнее загружается, и его нужно масштабировать, но мы видим, что оно верно классифицировано как камень. Также я могу загрузить все файлы сразу, и посмотреть классификацию для них всех. Давайте попробуем. Я ускорю видео, чтобы быстро миновать загрузку. Давайте посмотрим на полученные результаты классификации. Помним, что нейроны идут в таком порядке: бумага, потом камень, потом ножницы, — потому что он алфавитный. Итак, мы видим, что первый определился верно. Это ножницы. Но второй — неверно: это бумага, но наибольшее значение — у третьего нейрона, близкое к единице. А крошечного сигнала в "бумажном" нейроне даже близко недостаточно. Третий — ножницы, и это верно, аналогично для четвёртого и пятого. Продолжим просматривать по списку. Большинство выглядит верно. Пока мы не достигнем файла paper5.png, который, как и ранее, ошибочно классифицирован как ножницы. Давайте посмотрим на изображение. Это очевидно плоская рука. Возможно, что-то в её внешнем виде напоминает ножницы? У модели очень длинные пальцы. Paper9 тоже классифицировано как ножницы, и это очень похожее изображение, особенно, как вы видите, похожи промежутки между пальцами. Давайте посмотрим ещё несколько изображений. Вот ещё одна бумага, которую неправильно классифицировали, и изображение выглядит вот так. Оно очень отличается от других. Но при этом, первые два пальца очень похожи на ножницы. Все последующие данные, похоже, классифицированы правильно. Итак, мы посмотрели на мультиклассовую классификацию. Надеюсь, вам было интересно.

9(w4)-What have we seen so far?: (16.MLg_2c)

You're coming to the end of Course 2, and you've come a long way! From first principles in understanding how ML works, to using a DNN to do basic computer vision, and then beyond into convolutions.
With convolutions, you then saw how to extract features from an image, and you saw the tools in TensorFlow and Keras to build with convolutions and pooling as well as handling complex, multi-sized images.
Through this, you saw how overfitting can have an impact on your classifiers, and explored some strategies to avoid it, including image augmentation, dropout, transfer learning, and more. To wrap things up, you looked at the considerations in your code to build a model for multi-class classification!
---------------------------------------------------------------
Вы подходите к концу курса 2, и вы прошли долгий путь! От первых принципов в понимании того, как работает машинное обучение, до использования DNN для базового компьютерного зрения, а затем до сверток.
С помощью сверток вы увидели, как извлекать функции из изображения, и вы увидели инструменты в TensorFlow и Keras для построения с помощью сверток и объединения, а также для обработки сложных изображений разного размера.
Благодаря этому вы увидели, как переоснащение может повлиять на ваши классификаторы, и изучили некоторые стратегии, чтобы избежать этого, включая увеличение изображения, отсев, перенос обучения и многое другое. Подводя итог, вы рассмотрели соображения в своем коде, чтобы построить модель для классификации нескольких классов!

10(w4)- Week 4 Quiz: (16.MLg_2c)

1) The diagram for traditional programming had Rules and Data In, but what came out?:
1. Answers (+)
2. Binary
3. Machine Learning
4. Bugs
2) Why does the DNN for Fashion MNIST have 10 output neurons?:
1. To make it train 10x faster
2. To make it classify 10x faster
3. Purely Arbitrary
4. The dataset has 10 classes(+)
3)What is a Convolution?:
1. A technique to make images smaller
2. A technique to make images larger
3. A technique to extract features from an image(+)
4. A technique to remove unwanted images
4) Applying Convolutions on top of a DNN will have what impact on training?:
1. It will be slower
2. It will be faster
3. There will be no impact
4. It depends on many factors. It might make your training faster of slower, and a poorly designed Convolytiional layer may even be less efficient than a lain DNN(+)
5) What method on an ImageGenerator is used to normalize the image?:
1. normalize
2. flatten
3. rezize()
4. rescale (+)
6) When using Image Augmentation with the ImageDataGenerator, what happens to your raw image data on-disk.:
1. A copy will be made, and the copies are augmented
2. A copy will be made, and the originals will be augmented
3. Nothing (+)
4. The images will be edited on disk, so be sure to have a backup
7) Can you use Image augmentation with Transfer Learning?:
1. No - because the layers are frozen so they can't be augmented
2. Yes. It's pre-trained layers that are frozen. So you can augment your images as you train the bottom layers of the DNN with them (+)
8) When training for multiple classes what is the Class Mode for Image Augmentation?:
1. class_mode='multiply'
2. class_mode = 'non_binary'
3. class_mode = 'categorical'(+)
4. class_mode = 'all'

11(w4)-Lecture Notes Week 4: (16.MLg_2c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
opyright Notice
These slides are distributed under the Creative Commons License. DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
https://www.deeplearning.ai
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/convolutional-neural-networks-tensorflow/ungradedLti/XxU1e/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторском праве
Эти слайды распространяются по лицензии Creative Commons. DeepLearning.AI делает эти слайды доступными для образовательных целей.
https://www.deeplearning.ai
Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
https://www.deeplearning.ai
Остальные сведения о лицензии см.
https://creativecommons.org/licenses/by-sa/2.0/legalcode

11(w4)-Programming Assignment: Classification: Beyond two classes: (16.MLg_2c)

You have not submitted. You must earn 80/100 points to pass.
Deadline
The assignment was due on Jun 26, 9:59 AM EEST
You can still pass this assignment before the course ends.
Now that you've explored the concepts behind going from binary classification to multi class classification, it's time for another Exercise. In this one you'll use the Sign Language dataset from
https://www.kaggle.com/datamunge/sign-language-mnist
, and attempt to build a multi-class classifier to recognize sign language!
Let's build a multi-class classifier to recognize sign language!
Complete the tasks in the assignment notebook and upload the relevant files here for grading.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/assignment/C2W4_Assignment.ipynb#scrollTo=689f1257
This notebook is hosted on github so in order to save any changes you need to create a copy of it within your Drive. You can do so by clicking the `File` tab and then the `Save a copy in drive` option.
You should upload one file:
- The notebook (a file with .ipynb extension) which will be used to test the following functions:
parse_data_from_input
train_val_generators
create_model
IMPORTANT FOR SUCCESSFUL GRADING:
- Don’t delete cells as these include important metadata for grading.
- Fill out your solutions within the provided spaces. You can add new cells but these will be omitted by the grader.
---------------------------------------------------------------
Вы не представили. Вы должны заработать 80/100 очков, чтобы пройти.
Крайний срок
Задание должно было быть выполнено 26 июня в 9:59 по восточному поясному времени.
Вы все еще можете сдать это задание до окончания курса.
Теперь, когда вы изучили концепции перехода от бинарной классификации к многоклассовой, пришло время для другого упражнения. В этом вы будете использовать набор данных языка жестов из
https://www.kaggle.com/datamunge/sign-language-mnist
, и попытайтесь создать многоклассовый классификатор для распознавания языка жестов!
Давайте создадим многоклассовый классификатор для распознавания языка жестов!
Выполните задания в тетради с заданиями и загрузите сюда соответствующие файлы для оценивания.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C2/W4/assignment/C2W4_Assignment.ipynb#scrollTo=689f1257
Этот блокнот размещен на github, поэтому для сохранения любых изменений вам необходимо создать его копию на вашем Диске. Вы можете сделать это, щелкнув вкладку «Файл», а затем опцию «Сохранить копию на диске».
Вы должны загрузить один файл:
- Блокнот (файл с расширением .ipynb), который будет использоваться для тестирования следующих функций:
parse_data_from_input
train_val_generators
create_model
ВАЖНО ДЛЯ УСПЕШНОЙ ОЦЕНКИ:
- Не удаляйте ячейки, так как они содержат важные метаданные для оценивания.
- Заполните свои решения в предоставленных местах. Вы можете добавить новые ячейки, но они будут пропущены оценщиком.

12(w4)-Wrap up: (16.MLg_2c)

Congratulations on finishing Course 2 of this Specialization! Here, you spent a lot of time going over Convolutional Neural Networks:
exploring how to use them with large datasets
taking advantage of augmentation, dropout, regularization, and transfer learning
and of course, looking at the coding considerations between binary or multi-class classification
In Course 3, you'll switch gears and continue with Natural Language Processing, and in particular, work with texts.
---------------------------------------------------------------
Поздравляем с окончанием 2-го курса этой специализации! Здесь вы потратили много времени на сверточные нейронные сети:
изучение того, как использовать их с большими наборами данных
использование преимуществ увеличения, отсева, регуляризации и трансферного обучения
и, конечно же, глядя на соображения кодирования между двоичной или многоклассовой классификацией
На курсе 3 вы переключитесь и продолжите обработку естественного языка и, в частности, работу с текстами.

13(w4)-video6: A conversation with Andrew Ng (16.MLg_2c)

Congratulations on coming to the end of this second course. Just cause you've learned how to build bigger confidence, how to implement data augmentation, how to implement transfer learning as well also how to use multi-class cross size but there's still a lot more to learn. Lot's the examples you've seen so far have used many computer vision. In the next course, you'll learn how to deal with natural language processing to how to work with texts. It's going to be a lot of fun switching gears as well from dealing with pixels to dealing with characters and dealing with words. We'll take a look at how to tokenize words, how to generate embeddings, so that we can learn off of embeddings. An embedding is where we can turn a word into basically a vector in a multi-dimensional space and from the direction that vector points in we can start ascertaining the semantics of that word. We'll be going into all of that and how words also work in sequence and different sequence models for learning what the context of a sentences and what the semantics of the sentence is, yeah. That sounds exciting. So I think natural language processing is really taking off partly because of deep learning. So in the next course, you'll learn a lot about that and give that built some of these exciting models yourself. So let's go to the next course.
---------------------------------------------------------------
Поздравляю с тем, что дошли до конца этого второго курса. Из этого курса вы узнали, как достичь большей надёжности, как реализовать аугментацию данных, как реализовать перенос обучения, а также — как использовать мультиклассовую классификацию. Но многое ещё лишь предстоит узнать. Многие примеры, которые вы уже видели, использовали компьютерное зрение. В следующем курсе вы узнаете, как работать с естественным языком, как работать с текстами. Будет очень увлекательно переключиться от работы с пикселями на работу с символами и словами. Мы посмотрим, как токенизировать слова, как генерировать эмбеддинги, мы многое узнаем про эмбеддинги. Эмбеддинг — это то, с помощью чего мы фактически превращаем слово в вектор в многомерном пространстве, и по направлению, куда этот вектор указывает, мы можем выяснить семантику этого слова. Мы углубимся во всё это: как слова работают в предложении, каковы различные модели последовательностей для изучения контекста предложения, и что такое семантика предложения. Это звучит потрясающе. Я думаю, работа с естественным языком действительно очень много приобрела благодаря глубокому обучению. Так что в следующем курсе вы узнаете многое об этом, и сами построите некоторые из этих впечатляющих моделей. Итак, давайте перейдем к следующему курсу.


17.MLg_3c


(w1)Sentiment in text (17.MLg_3c)

(Настроение в тексте)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video: 38 minutes
Self-study: 1h 27 min
Graded tasks (Tasks to be assessed): 2

(w1) Content (17.MLg_3c)

1. 2. 3. 4.

(w1) Introduction: (17.MLg_3c)

The first step in understanding sentiment in text, and in particular when training a neural network to do so is the tokenization of that text. This is the process of converting the text into numeric values, with a number representing a word or a character. This week you'll learn about the Tokenizer and pad_sequences APIs in TensorFlow and how they can be used to prepare and encode text and sentences to get them ready for training neural networks!
---------------------------------------------------------------
Первым шагом в понимании настроения в тексте и, в частности, при обучении нейронной сети для этого является токенизация этого текста. Это процесс преобразования текста в числовые значения, где число представляет слово или символ. На этой неделе вы узнаете об API-интерфейсах Tokenizer и pad_sequences в TensorFlow и о том, как их можно использовать для подготовки и кодирования текста и предложений, чтобы подготовить их к обучению нейронных сетей!

1(w1)-video1: Introduction, A conversation with Andrew Ng (17.MLg_3c)

Welcome back. In this course, you'll learn how to use TensorFlow to process texts for natural language processing. Unlike images, which come in these regular shaped tensors of pixel intensity values, Text is messier, there are long sentences, there are short sentences. Do you want to process individual characters alphabets or do you wanna process words? So in this course, you learn how to deal with all that. Yes. So like in our first week as well we're going to take a look at what it takes for you to process text because neural networks generally deal in numbers. The zero functions, calculating weights and biases is all numbers. So how are we going to convert our texts into numbers in a sensible way? Given a word like cat, how do you turn that into a set of numbers that you can feed into neural network? Exactly. Then if I have cat, then what's dog going to look like? All of those kind of things. Then multiple length sentences as well. How do we deal with padding them? Or if you've got like a body of words that you use for training, and then you have another body of words that you want to actually predict on, but you're going to have some words in this body that aren't in that one. How do you deal with out of vocabulary tokens and that kind of things? There's going to be a lot of fun. Yeah. So in this first week, you learn how to load in the texts, pre-process it and set up your data so it can be fed to a neural network. I'm really excited. In this course, you'll learn how to deal with texts using TensorFlow. So let's go on to the next video to get started.
---------------------------------------------------------------
Добро пожаловать. На этом курсе вы узнаете, как использовать TensorFlow для обработки текстов на естественном языке. В отличие от изображения, которое может быть представлено в виде регулярной матрицы (тензора) значений яркости пикселей, — текст обладает более сложной структурой, может содержать как длинные, так и короткие предложения. Возникает вопрос: хотим ли мы обрабатывать отдельные буквы алфавита или целые слова? Итак, в этом курсе вы узнаете, как это делается. К примеру, на первой неделе курса мы узнаем, что требуется для того, чтобы обрабатывать текст, потому что нейронные сети обычно оперируют числами. Функции ошибки, вычисление весов и отклонений — это все работа с числами. Каким образом преобразовать текст в числа осмысленным образом? К примеру, слово "кошка", как его перевести в набор чисел, которые можно подать в нейронную сеть? Именно. И если у меня есть преобразование для слова"кошка", то каким образом тогда будет преобразовано слово "собака"? И всё в таком же духе. Кроме того, предложения могут быть разной длины. Как работать с ними? Или, если у вас есть набор слов, которые используются для обучения, и другой набор слов, который вы хотите уметь предсказывать, то, скорее всего, некоторые слова из этого набора не будут представлены в обучающем. Как работать со словами, отсутствующими в словаре, и тому подобным? Это будет очень занимательно. На первой неделе, вы узнаете, как загружать тексты, предобрабатывать их и подготавливать данные таким образом, чтобы их можно было подать в нейронную сеть. Я поистине восхищён. В этом курсе вы узнаете, как работать с текстами при помощи TensorFlow. И чтобы приступить, давайте перейдем к следующему видео.

2(w1)-Where to find the notebooks for this course: (17.MLg_3c)

All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You can simply click the Open in Colab badge at the top of the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this Github repository under the C3 folder. If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
tensorflow-datasets==4.0.1
scikit-learn==1.0.1
pandas==1.1.5
matplotlib==3.2.2
seaborn==0.11.2
---------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы можете просто щелкнуть значок «Открыть в Colab» в верхней части неоцененных лабораторных работ, в то время как для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом репозитории Github в папке C3. Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

3(w1)-video2: Introduction (17.MLg_3c)

In the earlier courses in this specialization, you got an introduction to machine learning and deep learning with a heavy focus on computer vision problems. You learned about neural networks and how they can match patterns to perform classifications. And then how you can give them new data and have them predict what they might be seeing. You learned how to make that a little smarter for images using convolutions to identify the features in the images and classify based on those instead of just matching on raw pixels. This helped you classify images for more real world style ones instead of using a very controlled environment.
In this course we're going to go back to building models but we'll focused on text and how you can build classifier is based on text models. We'll start by looking at sentiment in text, and learn how to build models that understand text that are trained on labeled text, and then can then classify new text based on what they've seen.
When we were dealing with images, it was relatively easy for us to feed them into a neural network, as the pixel values were already numbers. And the network could learn parameters of functions that could be used to fit classes to labels. But what happens with text? How can we do that with sentences and words?
---------------------------------------------------------------
В предыдущих курсах специализации вы прослушали введение в машинное обучение и глубокое обучение c упором на задачи компьютерного зрения. Вы изучили нейронные сети и то, каким образом они могут находить соответствия для решения задач классификации. А затем узнали, каким образом подать на сеть новые данные и научить её догадываться, что на них видно. Вы узнали, как решить эту задачу для изображений более ловко, используя свертки для выделения признаков на изображении и классификации по этим признакам — взамен простого сравнения пикселей. Это помогло классифицировать более реалистичные изображения, а не только сильно ограниченные набором условий*. [где объект крупный и в центре - прим. перев.]
В этом курсе мы вернемся к построению моделей, но сосредоточимся на текстах и на том, как строить классификаторы для них. Мы начнем с рассмотрения эмоциональной окраски текстов, и узнаем, как построить модели для понимания текста, обучающиеся на размеченных данных, чтобы эти модели могли классифицировать новые тексты на основе уже виденных.
Когда мы работали с изображениями, для нас было несложно подать их в нейронную сеть, т.к. значения яркости пикселей уже являются числами. И нейронная сеть может подстроить параметры функций, которые в дальнейшем будут использоваться для классификации. Но как быть с текстами? Как мы можем работать с предложениями и словами?

4(w1)-video3: Word based encodings (17.MLg_3c)

We could take character encodings for each character in a set. For example, the ASCII values. But will that help us understand the meaning of a word? So for example, consider the word 'LISTEN' as shown here. A common simple character encoding is ASCII, the American Standard Code for Information Interchange with the values as shown here. So you might think you could have a word like LISTEN encoded using these values. But the problem with this of course, is that the semantics of the word aren't encoded in the letters. This could be demonstrated using the word 'SILENT ' which has a very different and almost opposite meaning, but with exactly the same letters. So it seems that training a neural network with just the letters could be a daunting task. So how about if we consider words? What if we could give words a value and have those values used in training a network? Now we could be getting somewhere. So for example, consider this sentence, I Love my dog. How about giving a value to each word? What that value is doesn't matter. It's just that we have a value per word, and the value is the same for the same word every time. So a simple encoding for the sentence would be for example to give word 'I' the value one. Following on, we could give the words 'Love', 'my' and 'dog' the values 2, 3, and 4 respectively. So then the sentence, I love my dog would be encoded as 1, 2, 3, 4. So now, what if I have the sentence, I love my cat? Well, we've already encoded the words 'I love my' as 1, 2, 3. So we can reuse those, and we can create a new token for cat, which we haven't seen before. So let's make that the number 5. Now if we just look at the two sets of encodings, we can begin to see some similarity between the sentences. I love my dog is 1, 2, 3, 4 and I love my cat is 1, 2, 3, 5. So this is at least a beginning and how we can start training a neural network based on words. Fortunately, TensorFlow and Keras give us some APIs that make it very simple to do this. We'll look at those next.
---------------------------------------------------------------
Мы могли бы взять коды символов для каждого символа из кодировки. К примеру, значения из ASCII. Но поможет ли это понять смысл слова? Так, например, рассмотрим слово "LISTEN" , как показано здесь. Широко используется кодировка символов ASCII, т.е., "American Standard Code for Information Interchange" [Стандартный Американский Код для Обмена Информацией - прим.], — и здесь показаны её значения. И можно решить, что достаточно закодировать LISTEN, используя эти значения. Но проблема, разумеется, в том, что семантика слова не заложена в буквы. Это можно проиллюстрировать с помощью слова 'SILENT': его смысл совсем другой, практически противоположный, но буквы в слове те же самые. И похоже, что обучение нейронной сети с использованием только букв — это сложная задача. Так, может, стоит рассматривать слова целиком? Что, если бы мы могли присвоить целому слову (числовое) значение, и использовать эти значения для обучения сети? Возможно, это нам что-то даст. К примеру, рассмотрим предложение: "I Love my dog." Давайте присвоим значение каждому слову. Что это за значения — без разницы. Просто каждому слову присвоено отдельное значение, и значения для одинаковых слов всякий раз одинаковы. Таким образом, чтобы закодировать предложение, мы, например, присвоим слову 'I' значение 1. Вслед за этим мы могли бы присвоить словам "Love", "my" и "dog" — значения 2, 3 и 4 соответственно. Тогда предложение "I love my dog" будет закодировано как 1, 2, 3, 4. Что, если теперь взять предложение: "I love my cat"? Мы уже присвоили словам "I", "love" и "my" значения 1, 2 и 3. Так что можно их переиспользовать, и дать новое значение слову "cat", которое мы ранее не встречали. Давайте присвоим ему значение 5. Если мы теперь посмотрим на два набора кодов, то заметим, что эти предложения похожи. "I love my dog" закодировано как 1, 2, 3, 4, а "I love my cat" как 1, 2, 3, 5. Итак, это уже кое-что, мы получаем возможность обучать нейросеть на основе слов. К счастью, TensorFlow и Keras предоставляют API, который сильно облегчает эту задачу. Мы поговорим о нём далее.

5(w1)-video4: Using APIs (17.MLg_3c)

Here's the code to encode the two sentences that we just spoke about. Let's unpack it line by line. Tensorflow and keras give us a number of ways to encode words, but the one I'm going to focus on is the tokenizer. This will handle the heavy lifting for us, generating the dictionary of word encodings and creating vectors out of the sentences. I'll put the sentences into an array. Note that I've already capitalized 'I' as it is at the beginning of the sentence. I then create an instance of the tokenizer. A passive parameter num wards to it. In this case, I'm using 100 which is way too big, as there are only five distinct words in this data. If you're creating a training set based on lots of text, you usually don't know how many unique distinct words there are in that text. So by setting this hyperparameter, what the tokenizer will do is take the top 100 words by volume and just encode those. It's a handy shortcut when dealing with lots of data, and worth experimenting with when you train with real data later in this course. Sometimes the impact of less words can be minimal and training accuracy, but huge in training time, but do use it carefully. The fit on texts method of the tokenizer then takes in the data and encodes it. The tokenizer provides a word index property which returns a dictionary containing key value pairs, where the key is the word, and the value is the token for that word, which you can inspect by simply printing it out. You can see the results here. Remember when we said that the word I was capitalized, note that it's lower-cased here. Here, I've added another sentence, 'You love my dog!' but there's something very different about it. I've added an exclamation after the word 'dog!' Now, should this be treated as a different word than just dog? Well, of course not. That's another thing that the tokenizer does for you. It strips punctuation out. So the results of the code that we saw earlier with this new corpus of data, will look like this. Notice that we still only have 'dog' as a key. That the exclamation didn't impact this, and of course, we have a new key for the word 'you' that was detected. So you've seen the beginnings of handling texts by creating word-based encodings of that text, with some very simple code intensive flow and keras. In the next video, we'll take a look at the code and see how it works.
---------------------------------------------------------------
На экране — программа, кодирующая те два предложения, о которых мы только что говорили. Давайте рассмотрим её построчно. TensorFlow и Keras предоставляют несколько способов кодировать слова, но я сосредоточусь на токенизаторе (tokenizer). Он выполнит за нас всю тяжелую работу по созданию кодового словаря для слов и созданию векторов из предложений. Здесь я помещаю предложения в массив. Обратите внимание, что я написал "Ι" c заглавной буквы, поскольку она в начале предложения. Затем я создаю экземпляр токенизатора и передаю в него параметр num_words (количество слов). Здесь я использую значение 100, которое слишком велико, так как в данных присутствуют только 5 различных слов. Но если вы создаёте набор для обучения на основе большого количества текстов, то обычно не знаете, сколько уникальных слов присутствует в этом тексте. И если задать такое значение гиперпараметра, тогда токенизатор возьмет 100 наиболее часто встречающихся слов, и закодирует их. Это удобно при работе с большим объемом данных, и стоит с ним поэкспериментировать, когда вы позднее в данном курсе будете обучать нейросеть на реальных данных. Иногда слова, встречающиеся редко, могут почти не влиять на точность обучения, но очень сильно увеличивать время обучения. Но используйте параметр осмотрительно. Далее метод 'fit_on_texts' токенизатора получает данные и кодирует их. У токенизатора есть поле 'word_index', возвращающее словарь, содержащий пары ключ-значение, где в качестве ключа — само слово, а в качестве значения выступает соответствующий ему токен. Вы можете изучить этот словарь, просто напечатав его. На слайде представлен результат. Помните , что слово 'I' было написано с заглавной буквы? Обратите внимание, что здесь она строчная. Есть и еще одна вещь, которую токенизатор делает за вас: он удаляет пунктуацию. Польза этой функции видна из следующего примера. Здесь я добавил еще одно предложение: 'You love my dog!' — но здесь есть одно существенное отличие. Я добавил восклицательный знак после слова "dog!". Следует ли считать это слово отличным от просто "dog"? Конечно, нет. Результат выполнения рассмотренной программы на этом новом наборе данных, будет выглядеть так. Обратите внимание, что в качестве ключа у нас по-прежнему только "dog". Восклицательный знак не повлиял на это, и, конечно, у нас появился новый ключ, для обнаруженного здесь слова "you". Итак, вы увидели, как начинается обработка текста через построение для этого текста в TensorFlow и Keras очень простого кода, основанного на словах. В следующем видео мы посмотрим на код и разберемся, как он работает.

6(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community!: (17.MLg_3c)

Hello!
We’ve created a community for you to:
Ask for help on assignments and other course content.
Discuss course topics.
Share your knowledge with other learners.
Build your network
Find out about exciting DeepLearning.AI news, events and competitions!
To go to the community for this course, tick the checkbox below indicating you agree to use the app responsibly, then click on the "Launch App” button.
If you are new to the community, click on the "Launch App" button to create your account and access our community.
We created this User Guide for you.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Be sure to check out the Code of Conduct community guidelines.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Having trouble accessing our community after clicking the “Launch App” button? Fill out this form to explain your issue and we will get back to you.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
We hope to see you in our community soon!
- The DeepLearning.AI team
This course uses a third-party app, [IMPORTANT] Have questions, issues or ideas? Join our Community!, to enhance your learning experience. The app will reference basic information like your name, email, and Coursera ID.
Coursera Honor Code
---------------------------------------------------------------
Привет!
Мы создали для вас сообщество, чтобы:
Попросите помощи в заданиях и другом содержании курса.
Обсудите темы курса.
Поделитесь своими знаниями с другими учащимися.
Создайте свою сеть
Узнайте о захватывающих новостях, событиях и конкурсах DeepLearning.AI!
Чтобы перейти к сообществу для этого курса, установите флажок ниже, указывающий, что вы согласны использовать приложение ответственно, затем нажмите кнопку «Запустить приложение».
Если вы новичок в сообществе, нажмите кнопку «Запустить приложение», чтобы создать учетную запись и получить доступ к нашему сообществу.
Мы создали это Руководство пользователя для вас.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Обязательно ознакомьтесь с принципами сообщества Кодекса поведения.
https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
Возникли проблемы с доступом к нашему сообществу после нажатия кнопки «Запустить приложение»? Заполните эту форму, чтобы объяснить вашу проблему, и мы свяжемся с вами.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
Надеемся скоро увидеть вас в нашем сообществе!
- Команда DeepLearning.AI
В этом курсе используется стороннее приложение. [ВАЖНО] Есть вопросы, проблемы или идеи? Присоединяйтесь к нашему сообществу!, чтобы улучшить свой опыт обучения. Приложение будет ссылаться на основную информацию, такую ​​как ваше имя, адрес электронной почты и идентификатор Coursera.
Кодекс чести Coursera

7(w1)-Check out the code! (Lab 1): (17.MLg_3c)

Ungraded Lab: Tokenizer Basics
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W1/ungraded_labs/C3_W1_Lab_1_tokenize_basic.ipynb

8(w1)-video5: Notebook for lesson 1 (17.MLg_3c)

So here you can see the code that we were looking at in the lesson. First of all, you're going to be using the tokenizer class and this tokenizer class can be found in tensorflow.keras.preprocessing.text. The tokenizer class is going to do all the heavy lifting for us of managing the tokens, turning the sentences into streams of tokens and all that kind of stuff. So let's just take a look at it to begin with. So here I have my list of sentences I just have, I love my dog and I love my cat, note that the I is capitalized. And what the tokenizer is then going to do is that when I create an instance of it, I'm going to pass it a number of words that I want to have as the maximum number of entries in the dictionary. So in this case there's only 5 different words as you can see here, I love my dog and then cat. So this numb words by being bigger than 5 is kind of redundant. But as you're using larger corpuses of texts, if you have thousands of sentences that you want to classify, it's hard for you to end up trying to figure out the unique number of words in all of them. And so what you can do is by passing this parameter and you can say just give me the most common 100 words in the entire corpus, give me the most common 1000 words or whatever. So I'm just defaulting it to 100 here, even though I really don't need any more than 5. Then when I call the fit on texts method of the tokenizer and I pass it this list, what it's going to do is a number of things. The first thing that we're going to be looking at is that it's going to create that word-index for us where the word-index is a list of key value pairs. Where the key is the word and the value is the token for that word and we can print that out here. Other things that it's going to do, we'll take a look at later on but things such as for example turning each of these sentences into a list of tokens instead of those. So you don't have to do that manually but let's just start with the word index. So when I run this code we'll see now that I love my dog. Cat is my dictionary. So it's tokenized, I love my dog and then it's realized that I already had I love in my so it didn't bother with them and then it gave me a token for cats. So I get cat here. And as mentioned in the video, one of the things was that we noticed that it has changed my upper case I to a lowercase I and it's making upper case and lower case that the same thing. So for example, if I were to change this to an I like this, I wouldn't get an additional token, I still just have one token for I. So it's making a case insensitive. In addition to that, of course it's removing punctuation and grammar, not least the spaces have been removed. It's tokenized into words. But for example, if I were to say I, love my cat like this, I will still only have the 5 tokens it's recognized I or for example, if I add a new sentence, you love my dog with an exclamation at the end of it. Now, when I tokenize this, the only thing that I'm going to get is a new one for the word you because it hasn't seen the word you before. As you can see here, we've added a you. So that's it for this basic tokenization. This is the first step that you're going to have in getting text based data ready for training neural networks. This is going to be used with something called an embedding later on. And but before we do that, we just want to look at getting our sentences next into token based lists and making those lists all the same size
---------------------------------------------------------------
Перед вами — код, который мы рассматривали на данном занятии. Прежде всего, мы используем класс Tokenizer, и этот класс можно найти в модуле tensorflow.keras.preprocessing.text. Класс Tokenizer возьмёт на себя всю основную работу по обработке токенов, преобразованию предложений в поток токенов, и так далее. Так что давайте сперва разберёмся с ним. Вот мой список предложений: "I love my dog" и "I love my cat". Обратите внимание, что I — с заглавной буквы. И вот что с ними будет делать Tokenizer: когда я создам его экземпляр, то передам в конструктор число слов — это нужная мне максимальная размерность словаря. Как видите, в нашем случае во входных данных — всего 5 различных слов: I, love, my, dog, cat. Так что значение num_words, превышающее 5, будет избыточным. Но при использовании более крупных корпусов текстов, когда нужно классифицировать тысячи предложений, будет непросто определить число уникальных слов по всему корпусу. И в таком случае можно, задавая этот параметр, указать: "Нужно взять только 100 слов, чаще всего используемых в корпусе", или взять 1000 самых частотных слов, и т.п. Так что здесь я заложу 100, хотя на самом деле мне пока нужно не более 5. Затем я вызываю у токенизатора метод fit_on_texts, передавая в него список. При этом выполняется ряд действий. Во-первых, внутри будет создан индекс слов word_index, представляющий собой список пар ключ-значение. Ключом выступает слово, а значением — его токен. Здесь мы выводим этот список. Кроме того, выполняются и другие действия, мы их рассмотрим чуть позже, скажу лишь, что это, например, преобразование каждого предложения в список токенов, так что не придётся это делать вручную. Пока же рассмотрим индекс слов. Если выполнить этот код, в результате мы видим словарь, содержащий I, love, my, dog и cat. Сначала было разобрано предложение "I love my dog", а затем оказалось, что слова I, love и my уже есть, так что незачем снова их брать, и нужен лишь новый токен для cat. Так что далее идёт cat. В числе прочего, я упоминал на уроке, что здесь I в верхнем регистре заменено на написание в нижнем, i. Тем самым верхний и нижний регистр сводятся к одному и тому же. Так, например, если заменить в этом предложении I на i, то дополнительного токена не появится, будет всё так же один токен для i. Так что здесь вводится нечувствительность к регистру. Кроме того, при обработке выбрасываются пунктуация и грамматика — во всяком случае, исключаются пробелы. Происходит разбивка на слова. И если я, например, напишу так: "I, love my cat" — то по-прежнему получу лишь 5 токенов, среди которых будет и 'i'. Если же добавить новое предложение с восклицательным знаком в конце: "You love my dog!" — то при его разборе на токены я получу лишь один новый, для слова "you", поскольку такого слова прежде не встречалось. Как видите, здесь добавилось 'you'. На этом завершаем общий обзор токенизации. Это первый шаг в подготовке текстовых данных к обучению на них нейронных сетей. Далее мы будем им пользоваться в сочетании с так называемыми эмбеддингами. Но перед этим нам нужно посмотреть, как преобразовать предложения в списки токенов, и что сделать, чтобы эти списки были одинаковой длины.

9(w1)-video6: Text to sequence (17.MLg_3c)

In the previous video, you saw how to tokenize the words and sentences, building up a dictionary of all the words to make a corpus. The next step will be to turn your sentences into lists of values based on these tokens. Once you have them, you'll likely also need to manipulate these lists, not least to make every sentence the same length, otherwise, it may be hard to train a neural network with them. Remember when we were doing images, we defined an input layer with the size of the image that we're feeding into the neural network. In the cases where images where differently sized, we would resize them to fit. Well, you're going to face the same thing with text. Fortunately, TensorFlow includes APIs to handle these issues. We'll look at those in this video. Let's start with creating a list of sequences, the sentences encoded with the tokens that we generated and I've updated the code that we've been working on to this. First of all, I've added another sentence to the end of the sentences list. Note that all of the previous sentences had four words in them. So this one's a bit longer. We'll use that to demonstrate padding in a moment. The next piece of code is this one, where I simply call on the tokenizer to get texts to sequences, and it will turn them into a set of sequences for me. So if I run this code, this will be the output. At the top is the new dictionary. With new tokens for my new words like amazing, think, is, and do. At the bottom is my list of sentences that have been encoded into integer lists, with the tokens replacing the words. So for example, I love my dog becomes 4, 2, 1, 3. One really handy thing about this that you'll use later is the fact that the text to sequences called can take any set of sentences, so it can encode them based on the word set that it learned from the one that was passed into fit on texts. This is very significant if you think ahead a little bit. If you train a neural network on a corpus of texts, and the text has a word index generated from it, then when you want to do inference with the train model, you'll have to encode the text that you want to infer on with the same word index, otherwise it would be meaningless. So if you consider this code, what do you expect the outcome to be? There are some familiar words here, like love, my, and dog but also some previously unseen ones. If I run this code, this is what I would get. I've added the dictionary underneath for convenience. So I really love my dog would still be encoded as 4, 2, 1, 3, which is 'I love my dog' with 'really' being lost as the word is not in the Word Index, and 'my dog loves my manatee' would get encoded to 1, 3, 1, which is just 'my dog my'.
---------------------------------------------------------------
В предыдущем видео вы видели, как токенизировать слова и предложения, создавать словарь всех слов, составляющих корпус. Следующий этап — преобразовать предложения в списки значений на основе этих токенов. Когда вы их получите, вам, вероятно, также понадобится обработать эти списки, не в последнюю очередь, для того, чтобы выровнять их по длине — в противном случае, их трудно будет использовать в обучении нейронной сети. Помните, когда мы работали с изображениями, то определяли размер входного слоя, равный размеру изображения, передаваемого в нейронную сеть? А когда изображения были разных размеров, мы масштабировали их к нужному размеру. При работе с текстом возникает та же задача. К счастью, у TensorFlow есть API для решения этих проблем. Мы рассмотрим его в этом видео. Давайте начнём с создания списка предложений, где предложения закодированы токенами, которые мы сгенерировали. Я обновил наш рабочий код до такого вида. Во-первых, я добавил ещё одно предложение в конец списка. Заметьте, что во всех предыдущих предложениях было по четыре слова. А это — подлиннее. Скоро мы используем его для демонстрации дополнения. А вот второй изменённый участок кода, где я просто вызываю метод токенизатора, чтобы перевести текст в последовательность, и он вернёт мне набор последовательностей. И если я запущу этот код, то вот что он выведет. Сверху — новый словарь. С новыми токенами для новых слов, таких как amazing, think, is и do. Внизу — мой список предложений, закодированных списками целых чисел, где слова заменены токенами. Например, "I love my dog" становится 4, 2, 1, 3. У метода texts_to_sentences есть одно большое удобство, заключающееся в том, что при вызове можно передать любой набор предложений, и он закодирует их по набору слов, которые узнал из текста, переданного в fit_on_texts. Если подумать чуть наперёд, это очень важная вещь. Если вы тренируете нейросеть на корпусе текстов, и у вас есть индекс слов для данного корпуса, тогда для использования выводов обученной сети придётся кодировать тексты, передаваемые ей, тем же самым индексом слов, иначе результат будет бессмыслицей. Итак, посмотрите на этот код, что он, по-вашему, выведет? Здесь есть несколько знакомых слов, как love, my и dog, но есть также несколько незнакомых. Если я запущу этот код, то вот что я получу. Я добавил ниже словарь для удобства. Итак, "I really love my dog" будет закодировано как 4, 2, 1, 3, что значит "I love my dog", а слово "really" потерялось, поскольку его нет в индексе. А "my dog loves my manatee" будет закодировано как 1, 3, 1, что значит "my dog my".

10(w1)-video7: Looking more at the Tokenizer (17.MLg_3c)

So what do we learn from this? First of all, we really need a lot of training data to get a broad vocabulary or we could end up with sentences like, my dog my, like we just did. Secondly, in many cases, it's a good idea to instead of just ignoring unseen words, to put a special value in when an unseen word is encountered. You can do this with a property on the tokenizer. Let's take a look. Here's the complete code showing both the original sentences and the test data. What I've changed is to add a property oov token to the tokenizer constructor. You can see now that I've specified that I want the token oov for outer vocabulary to be used for words that aren't in the word index. You can use whatever you like here, but remember that it should be something unique and distinct that isn't confused with a real word. So now, if I run this code, I'll get my test sequences looking like this. I pasted the word index underneath so you can look it up. The first sentence will be, i out of vocab, love my dog. The second will be, my dog oov, my oov Still not syntactically great, but it is doing better. As the corpus grows and more words are in the index, hopefully previously unseen sentences will have better coverage. Next up is padding. As we mentioned earlier when we were building neural networks to handle pictures. When we fed them into the network for training, we needed them to be uniform in size. Often, we use the generators to resize the image to fit for example. With texts you'll face a similar requirement before you can train with texts, we needed to have some level of uniformity of size, so padding is your friend there.
---------------------------------------------------------------
Итак, чему мы здесь научились? Прежде всего, нам требуется очень много обучающих данных, чтобы собрать большой словарный запас, иначе мы можем получить предложения вроде "my dog my" (моя собака моего), как у нас только что вышло. Во-вторых, во многих случаях полезнее не игнорировать неизвестные слова, а вставлять специальное значение, когда встречается неизвестное слово. Это можно задать специальным параметром токенизатора. Давайте посмотрим. Вот весь код, показывающий как исходные предложения так и тестовые данные. Я изменил его, добавив параметр oov_token в вызов конструктора токенизатора. Как видите, я указал, что хочу для слов, которых нет в индексе, использовать токен &lt;OOV&gt;, означающий "нет в словаре" [Out Of Vocabulary]. Вы можете использовать любое значение, только помните, что оно должно быть уникальным, чтобы его нельзя было перепутать с настоящим словом. Итак, если я сейчас запущу этот код, то получу вывод тестовых предложений в таком виде. Ниже я привёл индекс слов, чтобы можно было с ним сверяться. Первое предложение будет: "I &lt;нет_в_словаре&gt; love my dog". Второе будет: "my dog &lt;не_в_словаре&gt; my &lt;не в словаре&gt;". Всё ещё небезупречно синтаксически, но уже лучше. По мере того, как корпус растёт, и в индексе становится всё больше слов, есть надежда, что не попадавшиеся ранее фразы будут содержать меньше незнакомых слов. Переходим к выравниванию. Как мы уже говорили, когда строили нейросеть для работы с изображениями: чтобы подать их в сеть для тренировки, нам нужно было сделать их одного размера. Обычно для изменения размера изображений используют генераторы. При работе с текстами существует аналогичное требование: прежде чем обучать на текстах, нужно как-то обеспечить однородность по длине, и выравнивание вам в этом поможет.

10(w1)-video8: Padding (17.MLg_3c)

So I've made a few changes to the code to handle padding. Here's the complete listing and we'll break it down piece by piece. First, in order to use the padding functions you'll have to import pad sequences from tensorflow.keras.preprocessing.Sequence. Then once the tokenizer has created the sequences, these sequences can be passed to pad sequences in order to have them padded like this. The result is pretty straight forward. You can now see that the list of sentences has been padded out into a matrix and that each row in the matrix has the same length. It achieved this by putting the appropriate number of zeros before the sentence. So in the case of the sentence 5-3-2-4, it didn't actually do any. In the case of the longer sentence here it didn't need to do any. Often you'll see examples where the padding is after the sentence and not before as you just saw. If you, like me, are more comfortable with that, you can change the code to this, adding the parameter padding equals post. You may have noticed that the matrix width was the same as the longest sentence. But you can override that with the maxlen parameter. So for example if you only want your sentences to have a maximum of five words. You can say maxlen equals five like this. This of course will lead to the question. If I have sentences longer than the maxlength, then I'll lose information but from where. Like with the padding the default is pre, which means that you will lose from the beginning of the sentence. If you want to override this so that you lose from the end instead, you can do so with the truncating parameter like this. So you've now seen how to encode your sentences, how to pad them and how to use Word indexing to encode previously unseen sentences using out of vocab characters. But you've done it with very simple hard-coded data. Let's take a look at the coded action in a screencast and then we'll come back and look at how to use much more complex data.
---------------------------------------------------------------
Итак, я слегка изменил код, добавив выравнивание. Вот весь код, мы разберём его по частям. Во-первых, чтобы использовать выравнивание, нужно импортировать pad_sequences из tensorflow.keras.preprocessing.sequence. Затем, когда токенизатор создал последовательности, нужно передать их в pad_sequences, чтобы получить их одинаковой длины, как здесь. Результат довольно очевиден. Вы видите, что список предложений был дополнен до матрицы, и теперь все строки матрицы — одной и той же длины. Это достигнуто размещением соответствующего количества нулей перед каждым предложением. В случае предложения 5, 3, 2, 4, добавлены три нуля. А в случае более длинного предложения ничего не надо было делать. Вам могут часто попадаться примеры, когда выравнивание производится в конце предложения, а не перед словами, как здесь. Если вы, как и я, находите это более удобным, то можете изменить код вот так, добавив параметр padding='post'. Вы могли заметить, что ширина матрицы была равна длине самого длинного предложения. Но это можно изменить, использовав параметр maxlen. Например, если вы хотите, чтобы в предложении было не больше пяти слов, то установите maxlen=5, как здесь. Разумеется, отсюда следует вопрос: а если предложения будут длиннее maxlen, то я потеряю информацию, но с какого конца? Как и в случае с дополнением, значение по умолчанию — 'pre' (перед), это значит, что вы потеряете слова из начала предложения. Если вы хотите это изменить, чтобы терять слова в конце, то можете указать параметр truncating='post', как здесь. Итак, вы теперь увидели, как закодировать предложения, как их выравнивать, и как использовать индекс слов для кодирования ранее незнакомых предложений, используя специальный символ "нет_в_словаре". Но вы всё это делали на простейших зашитых в код данных. Давайте поглядим демонстрацию работы этого кода, а затем вернёмся и посмотрим, как использовать гораздо более сложные данные.

11(w1)-Check out the code! (Lab 2): (17.MLg_3c)

Ungraded Lab: Generating Sequences and Padding
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W1/ungraded_labs/C3_W1_Lab_2_sequences_basic.ipynb

12(w1)-video9: Notebook for lesson 2 (17.MLg_3c)

Let's take a look at some of the basic text preprocessing that we've been doing. First of all, we're going to use a couple of APIs in TensorFlow. There's the tokenizer and there's pad sequences. The tokenizer can be found in tensorflow.keras.preprocessing.text and pad sequences can be found in tensorflow.keras.preprocessing.sequence. Our initial corpus of work that we're going to tokenize based off of is listed here. This is my list of sentences. I love my dog, I love my cat. You love my dog, and do you think my dog is amazing? On the tokenizer, I'm going to instantiate a new tokenizer. I'm going to say the maximum number of words in its corpus should be 100. Obviously we have a less than 100 words here or 100 different, unique and distinct words here. I'm also going to specify them out of vocabulary token should look like this. I'm just going to say it's OOV. I can put anything I want in here. But it should be always something that you wouldn't expect to see in the body of text so that's why I put angle brackets and OOV like this. Next, when I say tokenizer.fitontexts sentences, what it will then do is it's going to generate a tokenizer by creating a unique set of key values for the unique words that are in here. I will become a key love or become a key, those kind of things. It's going to create a word index where there are key value pairs, where a word is the key and that key has a value. For example, love becomes a key, I becomes a key, dog becomes a key. Those kind of things. That word index, I can then pull out of the tokenizer just by calling its word index property. I can get a word index variable that we can take a look at. The next thing is to be able to use sequences is on the tokenizer. It will then turn the text sentences that it has into sequences, replacing each word in the sentence with the value of the key for that particular word. For example, if the word I may have the key 2, and love has the key 3. Instead of saying I love, I'd have 2, 3 in a sequence, that type of thing. That's going to give me the sequences. Next, I'm going to use pads sequences to make all of these sequences the same size or the same width. You see some of these sentences have four words in them. Some of them have more, I believe this got seven words in this one. When we're training a neural network, we do want to have all of the data to be the same size. If you remember when we were doing it with convolutional neural networks, in some cases, like with Fashion-MNIST, the data was always 28 by 28. Or in other cases, like with the cats and dogs or horses versus humans, we resized the data as we were loading it. Pads sequences is our friend for that. In this case, when I take pad sequences, I'm going to pass in the sequences that we just generated. I'm going to specify a couple of parameters, padding equal to post and truncation equals post. The idea with these is that if my sentence is shorter than the width of the array, it's going to pad my sentence. The default experience with pad sequences is that the padding will be before the sentence. For example, in this case we have seven words in the sentence. In this case we have four. All three of these sentences would be padded with three zeros before the tokens for the actual words in the sentence. It'll be 0,0,0 token for I, token for love, token for my, that kind of thing. By specifying padding equals post, we do it the other way round where the zeros come after the sentence. Now it's really up to you how you do it. I tend to prefer it to be after the sentence so I can read the sentence from the beginning because I read left to right. But it's up to you and your scenario. What do you think is best? The default is pre. I'm overriding the default here by specifying post. Similarly, if we decide to specify the width of the array that we're going to be using. For example, in this case there are seven words and we only want it to be five words by saying maxlen equals five, like this. What will then happen is the sentence will be truncated into five. The default behavior is to truncate from the beginning by specifying truncating equals post will truncate from the end. In this case, if the maxlen is five, we'll take the first five words; do you think my dog and we'll lose the last two words. If we didn't have truncating equals posts, it would default to pre or if we set it to pre like this, then it will take the last five words which is think my dog is amazing, that type of thing. I'm just going to change that back to post. I'm going to get rid of maxlen equals 5 for the moment. Then we'll print out the word index that we generated, the sequences that we generated, and the padding sequences that we generated. Let's run it now and we can take a look at them.
If you remember the sentences, I love my dogs, I love my cat, you love my dog, do you think my dog is amazing? Here's the word index that was generated from them. The out of vocabulary token is value 1, my is 2, love is 3, dog is 4, I is 5, etc. Now if we look at the sequences that are created for us. If you remember the first sentence was, I love my dog. If you look at 5,3,2,4, I is 5, love is 3, my is 2, dog is 4 The second sentence was, I love my cat. I is 5, love is 3, my is 2, cat is 7, etc. These are our four sentences have been encoded into these sequences. Now when we do the padded sequences so that we get them all the same size. If you can see here, our first three sentences are four in length. That's this, this, and this. You'll see that they've been padded into, of zero characters at the end to make the right length. Then our final sentence, which was the longer one, the matrix has the same width as that sentence. So if up here, if I had said maxlen equals five and run it. Now we'll see my padded sequences have changed so that the fours are only padded out by one character to make five. My final sentence, 8,6,9,2,4 has lost these last three characters to make it the same width because my truncating equals post. If I remove truncating equals post, and actually I remove padding equal to post as well. We can see what happens. We'll see now that because my padding is pre, these three shorter sentences are prefixed by a zero. Because my truncation is pre, we'll see we are taking the last five characters in this one. There's no padding needed, but the truncation is off the front. That's really how tokenizer and padding works to help you with your text preprocessing. There's some pretty cool stuff going on in there. Now the second thing was to take a look at words that the tokenizer wasn't fixed to. If you remember when we created the tokenizer and the list of tokens in here are just from these sentences. When we start looking at sentences that are different from these, for example, I really love my dog. Instead of I love my dog, we'll notice that we're going to get an out of vocabulary character for this, because this one hasn't been learned. This becomes pretty important later on as you're training neural networks with this data. Because if you're just going to train it on the tokens that are in here, it's going to get harder to classify sentences like these because there's words that the tokenizer hasn't seen before, and therefore that the neural network isn't going to be trained on. Again, it's a classic case of the more training data you have, the better. But let's take a look at how the tokenizer will behave in this scenario anyway. In this case, I'm going to create a test sequence from the test data where I'm just using tokenizer again and I'm passing in the test data to generate some sequences. I'm going to print those out and then I'm going to pad those. Again, you can see I'm padding them, I'm not specifying any behavior here. The maximum length will be the length of the longest sentence. Padding will be pre and truncation will be pre. If I run that and we take a look at them. Now we can see my test sequences gets quite interesting because I said I really loved my dog. My test sequence is 5, 1, 3, 2, 4. Five is I, one of course is the out of vocabulary token, and then 3,2,4 are love my dog. I blank, love my dog is what the test sequence with effectively look like. This sentence, my dog loves my manatee. The word loves is different from the word love so there's no token for it and of course there's no token for manatee. But we have seen my dog and my before. So we end up with 2,4,1,2,1. Two of course is my, four is dog, one is out of vocabulary, two is my, and one is out of vocabulary. I get my dog blank my blank. Then when I pad the sequences out using this code, the 5,3,1,4 will stay the same. The 2,4,1,2,1 will stay the same because the sentences are the same length, so no padding and they'll truncation is necessary. Of course, if I had said something here like maxlen equals 10, and then I run it. We'll get lots of padding and because the default padding experience is pre, it'll be padded beforehand. That's a basic look at how to use tokenizer and how to use pad sequences to do text preprocessing. In the next video, we're going to then take a look at loading much bigger datasets instead of just these simple hard-coded ones and taking a look at what tokenizer and padding we'll do for them
---------------------------------------------------------------
Давайте же рассмотрим действия по самой простой предобработке текста. Первое: мы будем пользоваться некоторыми функциями из TensorFlow. Так что импортируем здесь Tokenizer и pad_sequences. Tokenizer находится в модуле tensorflow.keras.preprocessing.text, а pad_sequences — в модуле tensorflow.keras.preprocessing.sequence. Далее идёт наш изначальный корпус текстов, с которым мы будем работать. Это список моих предложений: "I love my dog", "I love my cat", "You love my dog!" и "Do you think my dog is amazing?" Что касается токенизатора, то я создаю его новый экземпляр, и указываю, что максимальное число слов для данного корпуса должно быть 100. Очевидно, у нас меньше 100 слов, менее 100 различных, уникальных слов. Также я задаю отдельный токен "нет в словаре", который будет выглядеть так: это будет строка "<OOV>". Сюда можно подставить любое значение, какое захочется. Но оно обязательно должно быть таким, чтобы не было шансов встретить его в корпусе текстов — вот почему я использовал здесь OOV в угловых скобках. Далее следует строка tokenizer.fit_on_texts(sentences), где происходит разбивка на токены, состоящая в создании уникальной пары "ключ-значение" для каждого уникального слова в корпусе. Так что ключами станут слова "I", "love", и так далее. При этом будет создан индекс слов word_index, в котором и хранятся эти пары "ключ-значение", где ключом является слово, и ему соответствует некое значение. Так, например, "love" будет ключом, а также "I", "dog", и так далее. Данный индекс слов я затем получаю из токенизатора простым обращением к атрибуту word_index. Можно завести для него переменную word_index, чтобы изучать её содержимое. Следующим шагом для использования последовательностей токенов нужно превратить при помощи токенизатора имеющийся текст в последовательности, где каждое слово предложения заменяется на значение, соответствующее данному ключу. Так, например, у слова "I" может быть значение 2, а у слова "love" — 3, И тогда вместо "I love" получится последовательность [2, 3], и т.п. Вот так я получаю последовательности. Далее я применяю pad_sequences, чтобы все последовательности стали одного размера, одной длины. Как видите, в некоторых предложениях было по четыре слова, а в других — больше, вот в этом, кажется, их семь. Но при обучении нейронной сети нам нужно, чтобы все данные были одной размерности. Если помните, при работе со свёрточными нейронными сетями у нас в некоторых случаях, таких как набор Fashion-MNIST, данные всегда были размером 28x28. А в других случаях, как в наборах "кошки и собаки" и "лошади и люди", мы меняли размерность данных при их загрузке. В данном случае, нас выручает pad_sequences. Так что здесь при вызове pad_sequences я передаю в вызов последовательности, которые мы только что сгенерировали. Кроме того, я указываю ещё два параметра: padding='post' и truncating='post'. Их смысл в том, что когда предложение оказывается короче, чем размерность массива, то данное предложение будет дополнено. По умолчанию pad_sequences дополняет последовательность спереди. Например, в данном случае у нас в предложении семь слов, а в данном случае — четыре. Все эти три предложения будут дополнены тремя нулями перед токенами, соответствующими самим словам предложения. Так что будет 0, 0, 0, затем — токен для "I", токен для "love", для "my", и так далее. Задавая padding='post', мы делаем всё наоборот: нули добавляются после токенов предложения. Тут вам решать, как поступать. Лично я предпочитаю дополнение в конце предложения, чтобы можно было читать его начало, ведь я читаю слева направо. Но в вашем случае решать вам, как вам лучше. По умолчанию дополнение в начало, 'pre'. Я переопределяю значение по умолчанию, указав здесь 'post'. Аналогичным образом, если нам захотелось задать длину используемого массива — например, в данном случае слов семь, а нам захочется брать, скажем, всего пять слов, то задав параметр maxlen = 5, мы добьёмся того, что предложение будет обрезано до пяти слов. По умолчанию обрезка происходит в начале предложения, но если задать truncating='post', то обрезка будет идти с конца. Так, если для данного случая задать maxlen=5, то мы возьмём только первые пять слов: "Do you think my dog" — и потеряем последние два. Если бы мы не задали truncating='post', то по умолчанию оно равнялось бы 'pre' (или можно задать 'pre' явным образом) — и тогда будут использованы последние пять слов, то есть "think my dog is amazing", и т.п. Верну значение 'post' обратно и избавлюсь на время от maxlen=5. Теперь выведем построенный индекс слов и те последовательности, что мы сгенерировали, а также выровненные последовательности. Давайте запустим код и посмотрим результат.
Если помните, то предложения были такими: "I love my dog", "I love my cat", "You love my dog!" и "Do you think my dog is amazing?" И вот индекс слов, созданный по этим предложениям. Токен <OOV> получил значение 1, "my" — 2, "love" — 3, "dog" — 4, "i" — 5, и т.д. Если же посмотреть на созданные последовательности токенов, то, если помните, первым было предложение "I love my dog", и если посмотреть на 5,3,2,4, то "i" — это 5, "love" — это 3, "my" — 2, "dog" — 4. Вторым предложением было "I love my cat". "i" — это 5, "love" — это 3, "my" — 2, "cat" — 7, и т.д. Это четыре наших предложения, закодированные в виде последовательностей токенов. Если теперь выполнить их выравнивание, чтобы они все были одной длины, то, как вы здесь видите, первые три последовательности были длиной в 4 слова, вот они. Как видите, они были дополнены нулями в конце до нужной длины. А последнее предложение, самое длинное, сохранило прежнюю свою длину. Если же выше задать maxlen=5 и запустить код снова, то теперь видно, что выровненные последовательности изменились: те, что были длиной по четыре, дополнены лишь одним символом до пяти, а последнее предложение, 8,6,9,2,4, — потеряло последние два символа при приведении к единой длине, поскольку я задал truncating='post'. Если убрать truncating='post', а заодно и padding='post', то вот что будет. Поскольку теперь дополнение происходит в начало, трём более коротким предложениям предшествуют нули. А поскольку обрезка тоже идёт от начала, то мы видим, что в последнем предложении берутся последние пять элементов. Дополнять здесь не требуется, а вот обрезка идёт из начала. Вот так работают токенизатор и дополнение последовательностей, помогая подготовить текст. Довольно любопытная штука. Второй пунктом было посмотреть, какие слова не участвовали в построении индекса токенов. Если помните, когда мы создавали токенизатор и список токенов, то использовали только эти предложения. И если брать предложения, отличающиеся от исходных, например, "I really love my dog", вместо "I love my dog", то мы увидим, что здесь появится символ "нет в словаре" для "really", потому что этого слова не было при обучении. Далее этот момент будет играть важную роль при обучении нейронной сети на таких данных, ведь если обучать её только на имеющихся здесь токенах, то будет нелегко классифицировать предложения вроде этих двух, потому что в них есть слова, которых токенизатор прежде не встречал, и потому нейросеть на них не будет обучена. Это ещё один классический случай, когда чем больше обучающих данных — тем лучше. Но давайте всё-таки посмотрим, как токенизатор поведёт себя в данном случае. Здесь я создаю тестовую последовательность на основе тестовых данных, при этом повторно используя токенизатор и передавая ему тестовые данные для построения последовательностей. Я их выведу, а затем применю к ним выравнивание. Как видите, здесь при выравнивании я не задаю никаких параметров. Поэтому в качестве максимальной длины будет использована длина самого длинного предложения, дополнение будет происходить спереди, и обрезка тоже. Запустим код и посмотрим, что вышло. Мы видим, что тестовые последовательности выглядят довольно любопытно, ведь я сказал "I really love my dog", и получилась последовательность 5, 1, 3, 2, 4. 5 — это "i", а 1 — это, разумеется, токен <OOV>, а 3, 2, 4 — это "love", "my", "dog". Так что в результате тестовая последовательность выглядит так: "I _ love my dog". А в следующем предложении, "My dog loves my manatee", слово "loves" отличается от слова "love", так что для него нет токена, а также, разумеется, его нет и для "manatee". Но "my", "dog" и "my" мы уже встречали, так что получается 2, 4, 1, 2, 1. 2 — это, разумеется, "my", 4 — "dog", 1 — это "нет в словаре", 2 — "my", и снова 1 — OOV. Итого, я получил: "My dog _ my _". Затем я выравниваю эти последовательности данной строкой кода, и 5, 1, 3, 2, 4 остаётся без изменений, и 2, 4, 1, 2, 1 — тоже без изменений, потому что эти последовательности — одинаковой длины, и не нужно ни дополнения, ни обрезки. Разумеется, если здесь задать, скажем, maxlen=10, и запустить этот код, то появится масса дополнительных символов, и поскольку по умолчанию дополнение идёт в начало, то дополнение произойдёт в начало. Мы посмотрели в общих чертах, как пользоваться токенизатором и выполнять выравнивание последовательностей при подготовке текстов. В следующем видео мы посмотрим загрузку более крупных наборов данных вместо данных простых наборов, заданных в коде. А также посмотрим, что с ними сделают токенизатор и выравнивание.

13(w1)-video10: Sarcasm, really? (17.MLg_3c)

So far this week, you've been looking at texts, and how to tokenize the text, and then turn sentences into sequences using the tools available in TensorFlow. You did that using some very simple hard-coded sentences. But of course, when it comes to doing real-world problems, you'll be using a lot more data than just these simple sentences. So in this lesson, we'll take a look at some public data-sets and how you can process them to get them ready to train a neural network. We'll start with this one published by Rishabh Misra with details on Kaggle at this link. It's a really fun CC0 public domain data-set at all around sarcasm detection. Really? Yeah, really. This data-set is very straightforward and simple, not to mention very easy to work with. It has three elements in it. The first is sarcastic, is our label. It's a one if the record is considered sarcastic otherwise it's zero. The second is a headline, which is just plain text and the third is the link to the article that the headline describes. Parsing the contents of HTML, stripping out scripts, and styles, etc, is a little bit beyond the scope of this course. So we're just going to focus on the headlines. If you download the data from that Kaggle site, you'll see something like this. As you can see, it is a set of list entries with name-value pairs where the name is article link, headline and is_sarcastic and the values are as shown. To make it much easier to load this data into Python, I made a little tweak to the data to look like this, which you can feel free to do or you can download my amended data-set from the link in the co-lab for this part of the course. Once you have the data like this, it's then really easy to load it into Python. Let's take a look at the code. So first you need to import JSON. This allows you to load data in JSON format and automatically create a Python data structure from it. To do that you simply open the file, and pass it to json.load and you'll get a list containing lists of the three types of data: headlines, URLs, and is_sarcastic labels. Because I want the sentences as a list of their own to pass to the tokenizer, I can then create a list of sentences and later, if I want the labels for creating a neural network, I can create a list of them too. While I'm at it, I may as well do URLs even though I'm not going to use them here but you might want to. Now I can iterate through the list that was created with a for item in data store loop. For each item, I can then copy the headline to my sentences, the is_sarcastic to my labels and the article_link to my URLs. Now I have something I can work with in the tokenizer, so let's look at that next.
---------------------------------------------------------------
Итак, на этой неделе вы смотрели на тексты, на то, как токенизировать тексты и затем превращать предложения в последовательности, используя инструменты, доступные в TensorFlow. Вы делали это, используя очень простые, жёстко запрограммированные предложения. Но, конечно, когда дело дойдёт до настоящих задач, вы будете использовать намного больше данных, чем только эти простые предложения. Итак, в этом уроке мы посмотрим на несколько общедоступных наборов данных и на то, как их обработать, чтобы на них можно было тренировать нейросеть. Мы начнём с данных, которые опубликовал на Kaggle Ришабх Мисра — подробности по этой ссылке. Это действительно забавный общедоступный набор данных (под лицензией CC0), посвящённый выявлению сарказма. Правда? Да, правда! Этот набор данных очень простой, не говоря уже о том, что с ним очень просто работать. В нём три элемента. Первый — наша метка, is_sarcastic (сарказм ли это). Она равна единице, если в строке есть сарказм, в противном случае это 0. Вторая — headline (заголовок), это просто текст. А третья — это ссылка на статью, которая была опубликована под этим заголовком. Скачивание содержимого HTML-страниц, очистка от скриптов, стилей и т.п. — несколько выходит за рамки этого курса. Так что мы сосредоточимся только на заголовках. Если вы скачаете данные с сайта Kaggle, то увидите что-то вроде этого. Как видите, это список, каждый элемент которого содержит пары имя-значение с именами article_link, headline и is_sarcastic, а значения подобны тем, что на экране. Чтобы проще было загрузить данные в Python, я немного подправил данные, чтобы они выглядели примерно так. Вы можете поступить так же, или же просто скачать по ссылке мой изменённый набор данных в colab для работы с ними в этой части курса. Получив данные, похожие на эти, загрузить их в Python очень просто. Давайте посмотрим на код. Сначала вам нужно импортировать модуль json. Это позволит вам загружать данные в формате json и автоматически превращать их в структуры данных языка Python. Чтобы сделать это, просто откройте файл и передайте его в функцию json.load — и вы получите список, содержащий списки значений трёх типов: заголовки, URL-адреса и метки is_sarcastic. Поскольку я хочу получить предложения в виде списка, без лишней информации, чтобы передать их в токенизатор, я создаю список предложений, а позже, когда мне для построения нейросети понадобятся метки — я сделаю и список меток тоже. И раз уж я занялся этим, сделаю заодно и список URL, хотя я и не собираюсь их тут использовать, но вдруг вы захотите это сделать. Теперь я могу пройтись по созданному списку значений циклом "for item in datastore". Для каждого элемента я скопирую заголовок в список sentences, метку is_sarcastic — в список labels, а ссылку на статью — в список urls. Теперь у меня есть данные, которые можно обработать токенизатором, так что давайте на это посмотрим.

14(w1)-video11: Working with the Tokenizer (17.MLg_3c)

This code is very similar to what you saw in the earlier videos, but let's look at it line by line. We've just created a sentences list from the headlines, in the sarcasm data set. So by calling tokenizer.fit_on_texts, will generate the word index and we'll initialize the tokenizer. We can see the word index as before by calling the word index property. Note that this returns all words that the tokenizer saw when tokenizing the sentences. If you specify num words to get the top 1000 or whatever, you may be confused by seeing something greater than that here. It's an easy mistake to make, but the key thing to remember, is that when it takes the top 1000 or whatever you specified, it does that in the text to sequence this process. Our word index is much larger than with the previous example. So we'll see a greater variety of words in it. Here's a few. Now we'll create the sequences from the text, as well as padding them. Here's the code to do that. It's very similar to what you did earlier, and here's the output. First, I took the first headline in the data set and showed its output. We can see that it has been encoded with the values for the keys that are the corresponding word in the sentence. This is the size of the padded matrix. We had 26,709 sentences, and they were encoded with padding, to get them up to 40 words long which was the length of the longest one. You could truncate this if you like, but I'll keep it at 40. That's it for processing the Sarcasm data set. Let's take a look at that in action in a screen cast.
---------------------------------------------------------------
Этот код очень похож на тот, что вы видели в предыдущих видео, Но давайте рассмотрим его построчно. Мы только что создали список предложений из заголовков на наборе данных, посвящённом сарказму. Вызов функции tokenizer.fit_on_texts сгенерирует словарь и настроит токенизатор. Как и раньше, можно посмотреть получившийся словарь, обратившись к свойству word_index. Обратите внимание, что словаре содержатся все слова, которые токенизатор получил в списке предложений. Если задать значение параметра num_words=1000 или что-то в этом духе, вас может смутить то, что в word_index слов окажется больше. Здесь нетрудно ошибиться, но главное — запомнить, что когда токенизатор берёт наиболее часто встречающуюся тысячу слов (или сколько вы зададите) — то делает он это во время вызова функции text_to_sequences. [а не fit_on_texts - прим. пер.] Наш словарь намного больше, чем в предыдущем примере. Так что мы увидим в нём куда большее разнообразие слов. Вот некоторые из них. Далее мы делаем из текста последовательности и выравниваем их. Вот код, который это делает. Он очень похоже на то, что вы сделали раньше. А здесь вывод результатов. Сначала я взял первый заголовок из набора данных — и показал, во что он преобразован. Мы видим, что он закодирован значениями, которые соответствуют словам в предложении. А это размер дополненной матрицы. У нас 26 709 предложений, и они закодированы с выравниванием до длины в 40 слов, что является длиной самого длинного предложения. Вы можете уменьшить длину, если хотите, но я оставлю 40. Вот мы и обработали набор данных, посвящённый сарказму. Давайте посмотрим демонстрацию его работы.

15(w1)News headlines dataset for sarcasm detection: (17.MLg_3c)

The following is the public domain dataset based on sarcasm, as depicted in the previous video.
The link is provided here for your convenience:
Sarcasm in News Headlines Dataset by Rishabh Misra
https://www.kaggle.com/datasets/rmisra/news-headlines-dataset-for-sarcasm-detection
---------------------------------------------------------------
Ниже приведен общедоступный набор данных, основанный на сарказме, как показано в предыдущем видео.
Ссылка дана здесь для вашего удобства:
Сарказм в наборе данных заголовков новостей от Rishabh Misra
https://www.kaggle.com/datasets/rmisra/news-headlines-dataset-for-sarcasm-detection

16(w1)Check out the code! (Lab 3): (17.MLg_3c)

Ungraded Lab: Tokenizing the Sarcasm Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W1/ungraded_labs/C3_W1_Lab_3_sarcasm.ipynb

17(w1)-video12: Notebook for lesson 3 (17.MLg_3c)

Okay, so let's take a look at the code.
So the first thing I'm going to do is download the modified dataset. So I modified the dataset from Kaggle as I showed in the video to create this sarcasm.json.which just makes it a little bit easier for us to load in python.
So then I import JSON and by importing JSON that gives me access to this object that I can call json.load and it makes life really simple for me that I've downloaded my file, I've stored it in slash TMP slash sarcasm.json. And then I can say by opening that as F. I can create this list called data store by saying json dot load F. And now all the data has been loaded for me. For tokenizing I want to pull out the headlines in two sentences and later when we're using a neural network to classify them, I will create labels from those from the ratings within the dataset. So I may as well just take that out the ratings I'm calling what is sarcastic at zero or 1 and if you ever want to like explore the URLs. I'm not going to do that here. I can also just create a list of URLs and pull them out.
Then all I have to do is iterate across the data store that I just created and then for each item in the data store in my sentences list, I'm going to upend the headline to my labels list. I'm going to upend the sarcastic value and this will actually come out as an integer. So I don't need to do any casting or changing and from my URLs if I want them I can also append the article link. So now I have my sentences let's take a look at what it will take to tokenize them and the code for this should be very familiar by now. So I'm going to import tokenizer from tensorflow keras that pre processing dot text. I'm going to import pad sequences from tensorflow keras pre processing dot sequence. I'm going to specify my out of vocabulary token and then I'm just going to fit on texts with the sentences. So now the sentences is the entire corpus of headlines.
I can take a look at my word index and I'm going to print the length of that word index and there's something really important here that we can discuss. And then I'll print the word index itself. Then finally I'm going to create a set of sequences to encode the words from these sentences into the values where the word is that particular key. And then I'm going to pad that out. I'm just going to keep this at default except for the fact that I'm going to pad post. So on shorter sentences I want to have zeros at the end and then print them out. So let's run this and see what happens.
So we can see it's downloaded my sarcasm.json. It's printed in this case 29657 was the print of the length of the word index which we see here. So there were 29657 unique words in this corpus. And then print out my word and next and we can see my out of vocabulary was 12 is 2 office 3, there's 4, those kind of things. And I then take a look at my sequences, I'll generate my sequence, I'll generate my padded and then I print out the padding for the first sentence just so we can see it. We can see the first sentence only had a few words in it and it got padded out with a lot of zeros. And then we'll see the size of my padded matrix that's coming out. So that's 26,709 sentences that have been encoded Into 40 integers percentage. That suggests to me that the longest sentence in the corpus was 40 words. And for example, this one where it's a bit shorter. It's padded it out with zeros extra. If I wanted to truncate it, I could have done that in the pad sequences. Now, one important thing is this word index. So a lot of time when we say when you're creating the word when you're creating the tokenizer and you're fitting it on text. You could specify the maximum number of words that you want. This word index will always be the same regardless of the number that you set for your maximum. So for example, had I set for a 100 words maximum, the word index would still have 29657. It would only take into account the 100 when it's actually creating the sequences. And then it will take my top 100 words and words that aren't in those top 100, then it would replace with the out of vocabulary. So one important thing and I'm not going to cover it here. But one important thing if you're doing this for real later on is that you'll see there's a lot of words here, like to and off and the and in and for which are going to be in your top 100. So if you're going to be truncating to the top number of words, you might want to get rid of a lot of like meaningless words like these and then focus on the more important words, the ones that have semantics for you. And it would actually, I think the easiest way to do that would be to remove them from the sentences themselves before you fit on texts. And then you don't have to worry about those words ending up in the index. But it's entirely up to you.
So that's it for this one. We'll move on to your exercise for the week, next
---------------------------------------------------------------
Давайте же заглянем в код.
Первым делом скачаем изменённый набор данных. Я переработал набор с Kaggle, который демонстрировал в лекции, подготовив sarcasm.json, который чуть проще будет загрузить в Python.
Импорт модуля json обеспечивает доступ к объекту json, у которого можно вызвать метод load, сильно упрощающий мне жизнь. Я сохранил скачанный файл в ./tmp/sarcasm.json. И теперь могу написать open(...) as f и создать список datastore, вызвав json.load(f). Теперь все данные подгружены. Для разбиения на токены нужно вытянуть заголовки в список sentences, далее мы будем использовать для их классификации нейронную сеть, так что я создаю метки на основе оценок, взятых из набора данных. Их можно взять напрямую из данных, выбирая атрибут is_sarcastic, равный 0 или 1. А также, если хотите, можно взглянуть и на URL. Я здесь не буду этим заниматься. Просто создам ещё один список с url, куда их и буду извлекать.
Нужно лишь пройтись по только что созданному datastore и из каждого его элемента взять заголовок и добавить его в список предложений sentences, а в список меток добавить значение is_sarcastic, являющееся целым числом, так что преобразования типов не требуется. А если мне нужны URL, то их можно взять из article_link. Итак, предложения я получил. Посмотрим, что будет, если их разбить на токены. Код уже должен быть вам хорошо знаком. Я импортирую Tokenizer из tensorflow.keras.prerpocessing.text, А также импортирую pad_sequences из tensorflow.keras.prerpocessing.sequence, после чего создам токенизатор, задав ему токен OOV ("нет в словаре"), после чего вызову fit_on_text(sentences). В sentences хранится весь набор заголовков.
Можно посмотреть содержимое индекса слов — я выведу его длину, которая, как мы обсуждали, играет важную роль. Затем я выведу значение самого word_index. Наконец, создам ряд последовательностей, кодирующих слова из данных предложений значениями, хранящимися по ключам, соответствующим словам. А затем выполню их выравнивание. Я оставлю настройки по умолчанию, за исключением выбора дополнения в конец. Тогда у более коротких предложений нули будут добавляться в конец. Выведем результат. Давайте запустим код и посмотрим, что будет.
Видим, как скачивается файл sarcasm.json. В данном случае выводится число 29657 — это длина индекса слов word_index, выводимая в этой строке. У нас в корпусе текстов 29657 уникальных слов. Далее выводим содержимое word_index и видим, что у <OOV> значение 1, "to" — 2, "of" — 3, "the" — 4, и т.д. Далее смотрим, какие получились последовательности после применения выравнивания. Я вывожу выровненный вариант для первого предложения, чтобы посмотреть его. Видно, что в этом первом предложении слов было немного, и оно было дополнено большим числом нулей. Ниже мы видим получившийся размер выровненной матрицы. У нас 29657 предложений, и каждое кодируется 40 целыми числами. Это подсказывает мне, что в самом длинном предложении корпуса было 40 слов. А это, например, оказалось покороче и было дополнено нулями. Если бы мне хотелось уменьшить размерность, это тоже можно было задать в pad_sequences. Один важный момент связан с индексом слов. Очень часто при создании токенизатора и его настройке на заданном корпусе текстов стоит указывать максимальное число используемых слов. Но индекс слов всегда будет одинаковым, независимо от того, какой максимум вы зададите. Так, скажем, если я задам максимум в 100 слов, то индекс слов всё равно будет содержать 29657. Этот лимит в 100 слов повлияет только на создаваемые последовательности. Тогда будут взяты 100 самый частотных слов, а слова, не попавшие в этот топ-100, будут заменяться на токен "нет в словаре". Так что важный момент, который я здесь подробно не разбираю, состоит в том, что на реальных задачах в индексе вы увидите массу слов, таких как "to", "of", "the", "in", попадающих в топ-100. Так что если вы будете сокращать словарь, оставляя самые частотные слова, то может потребоваться избавиться от подобных слов, не несущих смысла, и сосредоточиться на более важных, более осмысленных в вашем случае словах. На мой взгляд, проще всего это сделать, удалив нежелательные слова из самих предложений, перед подачей текста на токенизатор. Тогда не нужно будет заботиться о попадании таких слов в индекс. Но тут вам решать.
На этом мы закончили. Нас ждёт упражнение следующей недели.

18(w1)- Week 1 Quiz: (17.MLg_3c)

1) What is the name of the object used to tokenize sentences?:
1. Word Tokenizer
2. Tokenizer (+)
3. TextTokenizer
4. Character Tokenizer
2)What is the name of the method used to tokenize a list of sentences?:
1. fit_on_texts(sentences) (+)
2. tokenize_on text(sentences)
3. fit_to text(sentences)
4. tokenize(sentences
3) Once you have the corpus tokenises, what's the method used to encode a list of sentences to use those tokens?:
1. texts_to_sequences(sentences) (+)
2. text_to_sequences(sentences)
3. text_to_tokens(sentences)
4. texts_to_tokens(sentences)
4) When initializing the tokenizer, how do you specify a token to use for unknown words?:
1. oov_token=<Token> (+)
2. unknown_work=<Token>
3. out_of_vocab=<Token>
4. unknown_token=<Token>
5) If you don't use a token for out of vocabulary words, what happens at encoding?:
1. The word isn't encoded, and the sequencing ends
2. The word isn't encode, and is replaced by a zero in the sequence
3. The word is replaced by the most common token
4. The word isn't encoded, and is skipped in the sequence (+)
6) If you have a number of sequences of different lengths, how do you ensure that hey are understood when fed into a neural network?:
1. Make sure that they are all the same length using the pad_sequences method of the tokenizer (-)
2. Use the pad_sequences function from the tensorflow.keras.preprocessing.sequence namespace (+)
3. Process them in the input layer of the Neural Network using the pad_sequences property
4. Specify the input layer of the Neural Network to expect different sizes with dynamic_length
7) If you have a number of sequences of different length, and call pad_sequences on them, that's the default result?:
1. Nothing, they'll remain unchanged
2. They'll get padded to the length of the longest sequence by adding zeros to the beginning of shorter ones (+)
3. They'll get cropped to the length of the shortest sequence
4. They'll get padded to the length of the longest sequence by adding zeros to the end of shorter ones (-)
8) When padding sequences, if you want the padding to be at the end of the sequence, how do you do it?:
1. Pass padding='after' to pad_sequences when initializing it
2. Pass padding='post' to pad_sequences when initializing it (+)
3. Call the padding method of the pad_sequences object, passing it 'after'
4. Call the padding method of the pad_sequences object, passing it 'post'

19(w1)-video13: Week 1 Wrap up (17.MLg_3c)

This week, you looked at how to tokenize words, turning them into numbers, and using a dictionary to look up which word goes with which number. Next week, you'll take that to the next step using something called Embeddings, that takes these numbers and starts to establish sentiment from them, so that you can begin to classify and then later predict texts.
---------------------------------------------------------------
На этой неделе вы посмотрели, как токенизировать слова, превращать их в числа и использовать словари, чтобы посмотреть, какое слово соответствует какому номеру. На следующей неделе вы перейдёте к следующему шагу — использованию сущности под названием эмбеддинг, которая берёт эти числа и начинает извлекать из них эмоции, позволяя сначала классифицировать, а затем и предсказывать тексты.

20(w1)-Lecture Notes Week 1: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/natural-language-processing-tensorflow/ungradedLti/jF6xb/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License. DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
ou may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------
Конспекты лекций доступны на нашей платформе сообщества. Если вы уже являетесь участником, войдите в свою учетную запись и получите доступ к конспектам лекций здесь.
https://community.deeplearning.ai/логин
ПРИМЕЧАНИЕ. Если у вас еще нет учетной записи, следуйте приведенным здесь инструкциям, а затем вернитесь на эту страницу.
https://www.coursera.org/learn/natural-language-processing-tensorflow/ungradedLti/jF6xb/important-have-questions-issues-or-ideas-join-our-community
Уведомление об авторских правах
Эти слайды распространяются по лицензии Creative Commons. DeepLearning.AI делает эти слайды доступными для образовательных целей.
https://www.deeplearning.ai
Вы не можете использовать или распространять эти слайды в коммерческих целях. Вы можете делать копии этих слайдов и использовать или распространять их в образовательных целях, если вы указываете DeepLearning.AI в качестве источника слайдов.
Остальные сведения о лицензии см.
https://creativecommons.org/licenses/by-sa/2.0/legalcode

21(w1)-Assignment Troubleshooting Tips: (17.MLg_3c)

Here are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
1. For assignments that use Coursera Labs instead of Google Colab: Make sure to save your work before clicking the Submit button. If not, you might get an error message like in the code cell below. Remember that everything that you need to fill in within the graded functions is initialized to None.
Failed test case: x has incorrect type.
Expected:
some.Type,
but got:
<class 'NoneType'>.
2. For assignments that use Coursera Labs instead of Google Colab: Please do not rename the notebook. The grader will look for the original filename and its associated metadata so you should work on the file that is automatically opened when you click the Launch Notebook button. If you try to submit a renamed notebook, then you will likely also get an error like the one shown above.
3. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
4. After following the tips above and the grader still gives you 0/100, it's possible that the metadata needed for grading is corrupted. Please get a new lab notebook by refreshing your workspace (
instructions here). Then copy your solutions into the new notebook. Make sure that all cells still run as expected then resubmit.
5. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by following the instructions here. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
---------------------------------------------------------------
Ниже приведены некоторые общие рекомендации перед отправкой заданий в рамках этого курса. Пожалуйста, имейте это в виду не только для задания этой недели, но и для следующих:
1. Для заданий, которые используют Coursera Labs вместо Google Colab: обязательно сохраните свою работу, прежде чем нажимать кнопку «Отправить». В противном случае вы можете получить сообщение об ошибке, как в ячейке кода ниже. Помните, что все, что вам нужно заполнить в оценочных функциях, инициализируется значением None.
Неудачный тестовый пример: x имеет неправильный тип.
Ожидал:
какой-то.Тип,
но получил:
<класс 'Неттип'>.
2. Для заданий, которые используют Coursera Labs вместо Google Colab: не переименовывайте блокнот. Оценщик будет искать исходное имя файла и связанные с ним метаданные, поэтому вам следует работать с файлом, который автоматически открывается при нажатии кнопки «Запустить блокнот». Если вы попытаетесь отправить переименованный блокнот, вы, вероятно, также получите сообщение об ошибке, подобное показанному выше.
3. Пожалуйста, не изменяйте код вне тегов START CODE HERE и END CODE HERE. Ваше решение должно быть размещено только между этими маркерами, чтобы гарантировать успешное оценивание. Изменение параметров функции и других тестовых ячеек, скорее всего, приведет к поломке оценщика. Если вы хотите поэкспериментировать с ними, вы можете сделать это после того, как успешно пройдете задание.
4. Если после выполнения приведенных выше советов оценщик по-прежнему выдает вам 0/100, возможно, метаданные, необходимые для оценивания, повреждены. Получите новую лабораторную тетрадь, обновив рабочее пространство (
инструкции здесь). Затем скопируйте свои решения в новый блокнот. Убедитесь, что все ячейки по-прежнему работают должным образом, а затем повторите отправку.
5. Если у вас есть дополнительные вопросы, создайте тему в сообществе Discourse, а не на дискуссионных форумах Coursera. Вы можете присоединиться, следуя инструкциям здесь. Вы получите помощь там быстрее, потому что несколько наставников и ваших однокурсников следят за сообщениями. Просто убедитесь, что тема создана в правильной категории курса.

22(w1)-Refreshing your Workspace: (17.MLg_3c)

Most assignments in this course use Coursera Labs to provide a notebook environment and to grade your work. There might be some instances where you want to download your notebooks or refresh your workspace to start from scratch. This reading item outlines the steps to do so.
Downloading your Notebook
In case you need to download your notebook for troubleshooting or running in your local environment, you can follow these simple steps:
From the Menu Bar of the notebook you are working on, Click File → Save and Checkpoint to first save your progress.
Click File → Download as → Notebook (.ipynb). This should start downloading the file into your local machine.
Refreshing your Workspace
This will come in handy whenever you need to start from scratch, fetch the latest version of the assignment, or run into a 404 error.
Open the notebook from the classroom.
After the notebook opens up, click File → Open
When your workspace opens, tick the check box before your notebook file. After it is selected, press Shutdown. The icon beside the filename should turn from green to gray.
Tick the checkbox again and this time choose Rename and enter any filename other than the original. For example, C4W1_Assignment.ipynb (original) → C4W1_Assignment_v2.ipynb
(Optional) Tick the checkbox of any other file that you want to get a fresh copy of (e.g. dataset files that you might have manipulated irreversibly). Then click Delete . You can also opt to Rename or Download each file individually in case you want to keep them before deleting.
Click on the Help button on the top right of the page.
Click the Get latest version button.
Click the Update Lab button. The page will refresh and you should now see the latest version of the notebook.

22(w1)-Programming Assignment: Explore the BBC news archive: (17.MLg_3c)

Week 1: Explore the BBC News archive
https://www.coursera.org/learn/natural-language-processing-tensorflow/programming/lI0HI/explore-the-bbc-news-archive/lab?path=%2Fnotebooks%2FC3W1_Assignment.ipynb

NEXT week_2 (17.MLg_3c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2)Word Embeddings (17.MLg_3c)

(Вложения слов)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video: 30 minutes
Self-study: 2h 27 min
Graded tasks (Tasks to be assessed): 2

(w2) Content (17.MLg_3c)

1. TFDS - TensorFlow Data Services
2. IMDB в машинном обучении означает разработку модели, которая может автоматически определять тональность отзывов на фильмы на основе набора данных IMDB Movie Review
3. (RNN) - это тип нейронной сети, специально разработанный для работы с последовательными данными, такими как временные ряды, тексты или аудио.
4.

(w2) Introduction: (17.MLg_3c)

Last week you saw how to use the Tokenizer to prepare your text to be used by a neural network by converting words into numeric tokens, and sequencing sentences from these tokens. This week you'll learn about Embeddings, where these tokens are mapped as vectors in a high dimension space. With Embeddings and labelled examples, these vectors can then be tuned so that words with similar meaning will have a similar direction in the vector space. This will begin the process of training a neural network to understand sentiment in text -- and you'll begin by looking at movie reviews, training a neural network on texts that are labelled 'positive' or 'negative' and determining which words in a sentence drive those meanings.
---------------------------------------------------------------
На прошлой неделе вы видели, как использовать Tokenizer для подготовки вашего текста к использованию нейронной сетью путем преобразования слов в числовые токены и создания последовательности предложений из этих токенов. На этой неделе вы узнаете о встраиваниях, где эти токены отображаются как векторы в пространстве высокой размерности. Затем с помощью Embeddings и помеченных примеров эти векторы можно настроить так, чтобы слова с похожим значением имели одинаковое направление в векторном пространстве. Это положит начало процессу обучения нейронной сети понимать настроение в тексте — и вы начнете с просмотра обзоров фильмов, обучения нейронной сети на текстах, помеченных как «положительные» или «отрицательные», и определения того, какие слова в тексте предложения управляют этими значениями.

1(w2)-video1: A conversation with Andrew Ng (17.MLg_3c)

Welcome back. In this week, you'll learn how to use the Keras layer in TensorFlow to implement word embeddings, which is one of the most important ideas in Natural Language Processing. If you have a vocabulary size of say 10,000 words, rather than using the numbers from 1-10,000 to represent these words, can you have a better way to represent those numbers? So this week you'll learn about word embeddings and also get to train your own neural network for text classification. It's really interesting that I really liked how embeddings work for representing the semantics of a word. So now instead of the word just being a number, it's like a vector in n-dimensional space. We're using 16 and 32 dimensions in different examples. So for example the word dog, might be a vector pointing in a particular direction and then the word "canine", could be learned as a vector pointing in a very similar direction, and we know they have very similar semantic meaning off of that. All of this is actually done for us in embeddings. So as we train like our datasets, we'll train for example with IMDB which is movie reviews, and there's a set of positive reviews and a set of negative reviews, and what will actually happen is the embeddings for the words in these reviews, and we can actually plot them on a chart. So we'll see something that looks like a globe and one of the poles on the globe or all the words that are clustered around for the positive review, and all the words on the other pole of the globe are clustered around the negative review, and it really helps us to start to see the semantics behind these words. I think one of the coolest things about word embedding is you can download the pretrained word embedding that maybe someone else has trained. This gives your learning algorithm a hint into the meaning of these words. So when you see another vocabulary word, maybe you see "canine" for the first time, it's as if you can let the algorithm know that "canine" means something a little bit like dog related to dog even if you've never seen the word "canine" in your specific training. That's amazing. Today in the world of applied NLP, word embeddings has proved to be one of the most powerful and useful ideas to help teams get good performance. So in this week, you'll learn how to use word embeddings in TensorFlow. Let's go on to the next video.
---------------------------------------------------------------
С возвращением! На этой неделе вы научитесь использовать слои Keras в TensorFlow для работы с эмбеддингами, а это одно из самых важных понятий в работе с естественными языками. Если у вас есть словарь объёмом, скажем, 10 000 слов, то не лучше ли будет вместо использования чисел от 1 до 10 000 для их представления — найти взамен более удобный способ? Итак, на этой неделе вы узнаете про эмбеддинги, а также натренируете собственную нейросеть для классификации текстов. Любопытно: мне очень нравится, как эмбеддинги работают с семантикой слова. Вместо того, чтобы заменять слово просто на номер, мы представляем его вектором в n-мерном пространстве. В разных примерах мы используем 16 и 32 измерения. Например, слово "собака" может быть вектором, указывающим в некотором направлении, и слово K9 тоже при обучении может стать вектором, указывающим в очень похожем направлении, и мы из этого можем понять, что их значения очень похожи. И всё это организуют для нас эмбеддинги. И подобно тому, как мы тренировались на наших наборах данных, мы натренируем модель, например, на кинорецензиях с IMDB, там есть набор положительных рецензий и набор отрицательных рецензий, и мы сможем сделать вот что: соответствующие словам из рецензий эмбеддинги мы отобразим на графике. И увидим нечто, похожее на глобус, и на одном из полюсов глобуса будут все слова, сосредоточенные в положительных рецензиях, а все слова другого полюса глобуса сосредоточены в отрицательных рецензиях, и это очень поможет нам разглядеть семантику за этими словами. Я думаю, самое крутое в эмбеддингах — то, что вы можете скачать заранее натренированный набор эмбеддингов для слов, который, возможно, натренировал кто-то другой. И это даст вашей модели подсказку насчёт значения этих слов. И встречая слово, которого нет в словаре, скажем, впервые встретив слово K9, то с помощью эмбеддингов можно дать знать алгоритму, что K9 означает нечто, похожее на собаку, связанное с собаками, даже если у вас слово K9 вообще не встречалось в тренировочном наборе данных. Это потрясающе. На данный момент в мире прикладной обработки естественных языков эмбеддинги закрепились как одна из наиболее мощных и полезных концепций, и они помогают получить высокие результаты. Итак, на этой неделе вы научитесь использовать эмбеддинги в TensorFlow. Давайте перейдем к следующему видео.

2(w2)-video2: Introduction (17.MLg_3c)

Last week, you looked at tokenizing text. Where turn text into sequences of numbers with a number was the value of a key value pair with the key being the word. So for example, you could represent the word TensorFlow with the value nine, and then replace every instance of the word with a nine in a sequence. Using tools and TensorFlow, you are able to process strings to get indices of all the words in a corpus of strings and then convert the strings into matrices of numbers. This is the start of getting sentiment out of your sentences. But right now, it's still just a string of numbers representing words. So from there, how would one actually get sentiment? Well, that's something that can be learned from a corpus of words in much the same way as features were extracted from images. This process is called embedding, with the idea being that words and associated words are clustered as vectors in a multi-dimensional space. Here, I'm showing an embedding projector with classifications of movie reviews. This week, you'll learn how to build that. The reviews are in two main categories; positive and negative. So together with the labels, TensorFlow was able to build these embeddings showing a clear clustering of words that are distinct to both of these review types. I can actually search for words to see which ones match a classification. So for example, if I search for boring, we can see that it lights up in one of the clusters and that associated words were clearly negative such as unwatchable. Similarly, if I search for a negative word like annoying, I'll find it along with annoyingly in the cluster that's clearly the negative reviews. Or if I search for fun, I'll find that fun and funny are positive, fundamental is neutral, and unfunny is of course, negative. This week, you'll learn how to use embeddings and how to build a classifier that gave that visualization. You're most of the way there already with the work that you've been doing with string tokenization. We'll get back to that later but first let's look at building the IMDB classification that you just visualized.
---------------------------------------------------------------
На прошлой неделе вы посмотрели, как токенизировать тексты. Мы превращали тексты в последовательности чисел, где числа были значениями в паре "ключ-значение", а ключами были сами слова. Например, вы могли представить слово TensorFlow числом 9, и затем заменить каждое вхождение этого слова в последовательности на число 9. Используя TensorFlow и другие инструменты вы можете обработать строку так, чтобы получить числа для всех слов из корпуса текстов, а затем превратить эти тексты в матрицу с числами. Это начало того процесса, который измерит эмоциональную окраску предложений. А пока это просто последовательность чисел, представляющих слова. Как же можно получить отсюда эмоции? Их можно извлечь из корпуса слов способом, очень похожим на тот, которым признаки извлекаются из изображений. Этот процесс называется эмбеддингом, он основывается на представлении о том, что слова группируются вместе с другими связанными словами в виде векторов многомерного пространства. Здесь я показываю проекцию эмбеддинга, получившегося из классификации кинорецензий. На этой неделе вы узнаете, как построить такой эмбеддинг. Рецензии делятся на два основных подвида: положительные и отрицательные. Обладая метками, TensorFlow оказался способен построить эти эмбеддинги, выявляя отчётливую группировку слов, которыми эти два типа рецензий отличаются друг от друга. Я могу поискать слова, чтобы увидеть те из них, которые определяют различия. Например, я ищу слово "скучно", и мы видим, что оно подсвечивается в одной из этих групп, и что соседние с ним слова — отчётливо негативные, например, "невозможно смотреть". Точно так же, если я поищу негативное слово, такое как "раздражающий", я найду его недалеко от слова "раздражает", в группе с явно отрицательными рецензиями. А если я поищу слово "забавно", я увижу, что слова "забавно" и "забавный" положительные, "Основательно" — нейтральное, и "не смешно" — конечно, отрицательное. На этой неделе вы научитесь использовать эмбеддинги и строить классификатор, который даёт такую визуализацию. Вы уже проделали большую часть пути по обучению токенизации текстов. Мы вернёмся к этому позже, но сперва давайте посмотрим как построить классификатор рецензий на IMDB, визуализацию которого вы сейчас видели.

3(w2)-video3: The IMDB dataset (17.MLg_3c)

Part of the vision of TensorFlow to make machine learning and deep learning easier to learn and easier to use, is the concept of having built-in data sets. You seen the little bit of a preview of the way back in the first course, when the fashion MNIST was available to you without you needing to download and split the data into training a test sets. Expanding on this, there's a library called TensorFlow Data Services or TFDS for short, and that contains many data sets and lots of different categories. Here's some examples; and while we can see that there are many different data sets for different types, particularly image-based, there's also a few for text, and we'll be using the IMDB reviews dataset next. This dataset is ideal because it contains a large body of texts, 50,000 movie reviews which are categorized as positive or negative. It was authored by Andrew Mass et al at Stanford, and you can learn more about it at this link.
---------------------------------------------------------------
Частью подхода TensorFlow к тому, как сделать машинное обучение и глубокое обучение легче в освоении и проще в использовании, — является то, что у него есть встроенные наборы данных. Вы уже немного знакомились с ними ещё в первом курсе, когда использовали предоставляемый набор данных с изображениями одежды, без необходимости его скачивать и делить на тестовый и тренировочный наборы данных. В дополнение к этому, есть библиотека под названием TensorFlow Data Services, сокращённо TFDS, и в ней есть много наборов данных в множестве различных категорий. Вот несколько примеров. И хотя мы видим здесь много различных наборов с данными разных типов, в т.ч., с изображениями, — здесь также есть несколько с текстами, и мы будем дальше использовать набор данных imdb_reviews. Этот набор данных идеален, потому что он содержит большой массив текстов — 50 000 кинорецензий, которые разделены на положительные и отрицательные. Его составил Эндрю Мас с коллегами из Стэнфорда, вы можете узнать больше подробностей по этой ссылке.

4(w2)-IMDB reviews dataset: (17.MLg_3c)

Please find the link to the IMDB reviews dataset here.
You will find here 50,000 movie reviews that are classified as positive or negative.
http://ai.stanford.edu/~amaas/data/sentiment/
---------------------------------------------------------------
Ссылку на набор данных отзывов IMDB можно найти здесь.
Здесь вы найдете 50 000 отзывов о фильмах, которые классифицируются как положительные или отрицательные.
http://ai.stanford.edu/~amaas/data/sentiment/

5(w2)-video4: Looking into the details (17.MLg_3c)

So let's start looking at it. There are a couple of things that you need to take into account before you start working with this week's code in TensorFlow. The first is the version of TensorFlow you're using. Use this code to determine it. Also, do note that all the code I'm using here is in Python 3. There are some differences if you use Python 2. So if you're using a Colab, you can set the environment to three. If you're doing this in your own environment, you may need to make some changes. Now, you can import TensorFlow datasets, and in this case I call them tfds. With imdb reviews, I can now call tfds.load, pass it the string imdb reviews, and it will return the data from imdb, and metadata about it with this code. The data is split into 25,000 samples for training and 25,000 samples for testing. I can split them out like this. Each of these are iterables containing the 25,000 respective sentences and labels as tensors. Up to this point, we've been using the Keras tokenizers and padding tools on arrays of sentences, so we need to do a little converting. We'll do it like this. First of all, let's define the lists containing the sentences and labels for both training and testing data. Now, I can iterate over training data extracting the sentences and the labels. The values are tensors, so by calling their NumPy method, I'll actually extract their value. Then I'll do the same for the test set. Here's an example of a review. I've truncated it to fit it on this slide, but you can see how it is stored as a tf.tensor. Similarly, here's a bunch of labels also stored as tensors. The value 1 indicates a positive review and zero a negative one. When training, my labels are expected to be NumPy arrays. So I'll turn the list of labels that I've just created into NumPy arrays with this code. Next up, we'll tokenize our sentences. Here's the code. I've put the hyperparameters at the top like this for the reason that it makes it easier to change and edit them, instead of phishing through function sequences for the literals and then changing those. Now, as before, we import the tokenizer and the pad sequences. We'll create an instance of tokenizer, giving it our vocab size and our desired out of vocabulary token. We'll now fit the tokenizer on our training set of data. Once we have our word index, we can now replace the strings containing the words with the token value we created for them. This will be the list called sequences. As before, the sentences will have variant length. So we'll pad and or truncate the sequenced sentences until they're all the same length, determined by the maxlength parameter. Then we'll do the same for the testing sequences. Note that the word index is words that are derived from the training set, so you should expect to see a lot more out of vocabulary tokens in the test exam. Now it's time to define our neural network. This should look very familiar by now, except for maybe this line, the embedding. This is the key to text sentiment analysis in TensorFlow, and this is where the magic really happens.
---------------------------------------------------------------
Итак, давайте посмотрим на этот набор [IDMB]. Есть пара моментов, которые следует принять во внимание, прежде чем начать работать с кодом этой недели для TensorFlow. Первый — какую версию TensorFlow вы используете. Запустите эти строки, чтобы это выяснить. Также обратите внимание, что весь код, который я использую здесь, написан на Python 3. Если у вас Python 2, будут некоторые различия. Так что, если вы используете Colab, то можете настроить окружение на использование 3-й версии. Если вы работаете в собственном окружении, то вам могут понадобиться некоторые изменения. Если предыдущий код показал, что у вас версия TensorFlow 1.x, нужно запустить эту строку прежде чем выполнять дальнейшие действия. Если же он показал версию 2.x, вам ничего не надо делать, т.к. TensorFlow 2.0 активирует "стремительное исполнение" по умолчанию. Если вы используете Google Colab, тогда у вас, скорее всего, уже установлены наборы данных из TensorFlow. Но даже если нет, они легко устанавливаются данной строчкой кода. Теперь можно импортировать наборы данных TensorFlow, в данном случае, я назову их tfds. Для того, чтобы загрузить imdb_reviews, я могу вызвать tfds.load и передать ему строку "imdb_reviews", и он вернёт данные с IMDB, и их метаданные как результат вызова функции. Данные разбиты на 25 000 записей для обучения и 25 000 для тестирования. Я могу разделить их, запустив такую строку. Через каждый из массивов можно пройти в цикле, они содержат по 25 000 предложений и меток в виде тензоров. До этого момента мы использовали токенизатор и инструмент для выравнивания массивов предложений из Keras, так что нам нужно слегка преобразовать данные. Мы сделаем это так. Во-первых, давайте определим списки, содержащие предложения и метки — как для тренировочного набора данных, так и для тестового. Теперь можно пройтись по всему тренировочному набору данных, извлекая из него предложения и метки. s и l имеют тип "тензор", так что вызывая их метод numpy(), я извлекаю их значения. Затем я сделаю то же самое с тестовым набором данных. Вот пример рецензии. Я обрезал его, чтобы он уместился на слайде, но вы можете посмотреть, как он хранится в тензоре. Аналогично, вот группа меток, сохранённых как тензоры. Значение 1 обозначает положительную рецензию, а 0 — отрицательную. При обучении модели у меток должен быть тип массивов numpy. Поэтому я преобразую только что созданные списки меток в массивы numpy с помощью данного кода. Затем мы токенизируем предложения. Вот соответствующий код. Я вынес все гиперпараметры в одно место в начале, чтобы было легче менять и редактировать их, вместо того, чтобы продираться через последовательность функций в поисках конкретных значений, и затем менять их. Тут, как и раньше, мы импортируем tokenizer и pad_sequences. Мы создадим токенизатор, передадим ему размер словаря и токен, который мы хотим указать в качестве "нет_в_словаре". Теперь обучаем токенизатор на тренировочном наборе данных. Получив наш словарь с токенами, мы можем теперь заменить содержащие слова строки на полученные значения токенов, и поместить их в список под названием sequences. Как и раньше, предложения будут разной длины. Так что мы дополним или обрежем предложения, преобразованные в последовательности, пока они не окажутся одной длины, указанной в параметре max_length. Затем мы сделаем то же самое для тестовых последовательностей. Обратите внимание, что в словарь входят только слова из тренировочного набора, так что в тестовых последовательностях стоит ожидать большего числа токенов OOV. Теперь пора определить структуру нашей нейросети. К этому моменту вам уже всё должно быть знакомо. Кроме, возможно, первого пункта — Embedding. Это ключевой элемент анализа эмоций в текстах при помощи TensorFlow, и именно тут происходит настоящая магия.

6(w2)-video5: How can we use vectors? (17.MLg_3c)

The full scope of how embeddings work is beyond the scope of this course. But think of it like this. You have words in a sentence and often words that have similar meanings are close to each other. So in a movie review, it might say that the movie was dull and boring, or it might say that it was fun and exciting. So what if you could pick a vector in a higher-dimensional space say 16 dimensions, and words that are found together are given similar vectors. Then over time, words can begin to cluster together. The meaning of the words can come from the labeling of the dataset. So in this case, we say a negative review and the words dull and boring show up a lot in the negative review so that they have similar sentiments, and they are close to each other in the sentence. Thus their vectors will be similar. As the neural network trains, it can then learn these vectors associating them with the labels to come up with what's called an embedding i.e., the vectors for each word with their associated sentiment. The results of the embedding will be a 2D array with the length of the sentence and the embedding dimension for example 16 as its size. So we need to flatten it out in much the same way as we needed to flatten out our images. We then feed that into a dense neural network to do the classification. Often in natural language processing, a different layer type than a flatten is used, and this is a global average pooling 1D. The reason for this is the size of the output vector being fed into the Dense. So for example, if I show the summary of the model with the flatten that we just saw, it will look like this. Or alternatively, you can use a Global Average Pooling 1D like this, which averages across the vector to flatten it out. Your model summary should look like this, which is simpler and should be a little faster. Try it for yourself in colab and check the results. Over 10 epochs with global average pooling, I got an accuracy of 0.9664 on training and 0.8187 on test, taking about 6.2 seconds per epoch. With flatten, my accuracy was 1.0 and my validation about 0.83 taking about 6.5 seconds per epoch. So it was a little slower, but a bit more accurate. Try them both out, and experiment where the results for yourself.
---------------------------------------------------------------
Полный охват работы эмбеддингов выходит за рамки этого курса. Но думайте о них примерно так. У вас есть слова в предложении, и часто слова с похожими значениями стоят близко друг к другу. Так, в кинорецензии может говориться, что кино было скучным и унылым, или что оно было увлекательным и захватывающим. И можно взять вектор в многомерном пространстве — 16-мерном, например, то словам, стоящим в тексте рядом, можно назначить близкие вектора. Тогда со временем слова могут начать группироваться вместе. Значение слов может исходить из меток этого набора данных. В нашем случае, можно сказать, что в отрицательной рецензии слова "унылый" и "скучный" появляются часто, так что они выражают близкие эмоции, и они стоят близко друг к другу в предложении. Так что их векторы будут похожими. И по мере обучения нейросети, она может запомнить эти векторы и связать их с метками, получив то, что называется эмбеддингами, т. е. с вектора для каждого слова вместе со связанными с ними эмоциями. Результатом эмбеддинга будет двухмерный массив, чья длина совпадает с длиной предложения, а размерность эмбеддинга — будет, например, 16. Нужно сделать массив одномерным, так же, как мы делали с изображениями. Затем мы передаём результат в полносвязную нейросеть для классификации. Часто в обработке естественных языков вместо слоя flatten используется другой способ, а именно, глобальное усреднение по одной оси. Так делают, чтобы уменьшить размер вектора, который попадает в плотный слой, Например, если я покажу сводку по модели со слоем flatten, код которой мы видели, то она будет выглядеть так. Если мы взаме используем слой GlobalAveragePooling1D, как здесь, который усредняет поперёк вектора, чтобы сделать массив одномерным, то сводка по модели будет выглядеть так — что делает модель проще и должно работать побыстрее. Попробуйте сами в Colab и сравните результаты. Обучая в течение 10 эпох с усреднением, я получил точность 0.9664 на тренировочном наборе и 0.8187 на тестовом, и это заняло около 6.2 секунд на эпоху. С развёртыванием вектора (flatten) точность была 1.0, а на тестовом наборе данных — около 0.83, и около 6.5 секунд на эпоху. Так что стало чуть медленнее, но и чуть точнее. Попробуйте оба варианта и самостоятельно поэкспериментируйте с результатами.

6(w2)-video5: More into the details (17.MLg_3c)

You can compile your model as before, and print out the summary with this code. Now training is as simple as passing padded and your training labels final as your training set, specifying the number of epochs, and passing the testing padded and testing labels final as your test set. Here's the results of training, with the training set giving us 1.00 accuracy and the validation set at 0.8259. So there's a good chance that we're overfitting. We'll look at some strategies to avoid this later, but you should expect results a little bit like this. Okay. Now we need to talk about and demonstrate the embeddings, so you can visualize them like you did right back at the beginning of this lesson. We'll start by getting the results of the embeddings layer, which is layer zero. We can get the weights, and print out their shape like this. We can see that this is a 10,000 by 16 array, we have 10,000 words in our corpus, and we're working in a 16 dimensional array, so our embedding will have that shape. To be able to plot it, we need to reverse our word index. As it currently stands, our word index has the key being the word, and the value being the token for the word. We'll need to flip this around, to look through the padded list to decode the tokens back into the words, so we've written this function. Now it's time to write the vectors and their metadata auto files. The TensorFlow Projector reads this file type and uses it to plot the vectors in 3D space so we can visualize them. To the vectors file, we simply write out the value of each of the items in the array of embeddings, i.e, the co-efficient of each dimension on the vector for this word. To the metadata array, we just write out the words. If you're working in Colab, this code will download the two files. To now render the results, go to the TensorFlow Embedding Projector on projector.tensorflow.org, press the ''Load data'' button on the left. You'll see a dialog asking you to load data from your computer. Use vector.TSV for the first one, and meta.TSV for the second. Once they're loaded, you should see something like this. Click this ''sphereize data'' checkbox on the top left, and you'll see the binary clustering of the data. Experiment by searching for words, or clicking on the blue dots in the chart that represent words. Above all, have some fun with it. Next up, we'll step through a screencast of what you've just seen, so you can explore it in action. After that, you'll look at how TFDS has built in tokenizers that prevent you from writing a lot of the tokenizing code that we've just used.
---------------------------------------------------------------
Выполнив данный код, можно скомпилировать модель, как мы уже делали, и вывести сводку. Обучать проще простого: передаём списки padded и training_labels_final в качестве обучающей выборки, указываем количество эпох и передаём testing_padded и testing_labels_final в качестве валидационной выборки. Вот результаты обучения. На обучающей выборке точность получается 1.0, а на валидационной — 0.8259. Это говорит о том, что есть большая вероятность переобучения. Позже мы обсудим несколько стратегий, как его избежать, а пока стоит рассчитывать, что результаты будут похожи на эти. А сейчас нам надо обсудить и продемонстрировать эмбеддинги, чтобы вы могли их визуализировать, как это было в начале этого урока. Мы начнём с получения результатов слоя embeddings, т.е., слоя с индексом 0. Можно получить его веса и вывести их размерность, как здесь. Мы видим, что это матрица 10 000 на 16: в нашем корпусе 10 000 слов, и мы работаем с 16-мерным массивом, поэтому наши эмбеддинги приобрели такую форму. Чтобы их вывести на график, нам нужна вспомогательная функция, которая обращает индекс слов. Сейчас в нашем индексе слов ключом служит само слово, а значением — его токен. Нам нужно поменять их местами, чтобы в списке выровненных последовательностей заменять токены обратно на слова. Так что мы написали вот такую вспомогательную функцию. Теперь выведем векторы и метаданные в результирующие файлы. Утилита Projector в составе TensorFlow прочитает файлы данного типа и использует их, чтобы отобразить векторы в трёхмерном пространстве, так что мы сможем их визуализировать. В файл векторов мы просто запишем значение каждого из элементов массива эмбеддингов, т. е., коэффициенты всех измерений вектора для этого слова. А в массив метаданных мы просто запишем слова. Если вы работаете в Colab, то данный код скачает два файла. Чтобы теперь отобразить результаты, откройте TensorFlow Embedding Projector на projector.tensorflow.org, нажмите на кнопку Load data слева, и вы увидите диалог, предлагающий загрузить данные с вашего компьютера. Выберите в первом поле файл vector.tsv, а во втором — meta.tsv. Когда они загрузятся, вы должны увидеть что-то похожее на это. Поставьте галочку "Sphereize data" слева вверху, и вы увидите разбиение данных на два кластера. Попробуйте искать здесь слова или покликайте на голубые точки на графике, которые представляют слова. Словом, поиграйте с графиком. Далее мы пошагово пройдёмся по коду, делающему то, что вы только что видели, чтобы вы могли изучить код в действии. После этого мы разберём встроенный в TFDS токенизатор, позволяющий не писать массу того кода для токенизации, что мы только что использовали.

7(w2)-Check out the code! (Lab 1): (17.MLg_3c)

Ungraded Lab: Training a binary classifier with the IMDB Reviews Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W2/ungraded_labs/C3_W2_Lab_1_imdb.ipynb

8(w2)-video6: Notebook for lesson 1 (17.MLg_3c)

Okay so let's take a look at the code, that we're going to use in this environment. So the next thing I'm going to do is just import TensorFlow datasets as TFDS. On TFDS load, IMDb reviews will give me an IMDb set and an info set. I'm going to use the info set in another video, we're not going to use it here. But the IMDb set is what we're going to be looking at here. So next up is the code where I'm going to get my IMDb training and my IMDb testing and load them into training and test data. I'm going to create lists of training sentences and labels, testing sentences and labels, and I'm going to copy the contents of the tensors into these so that I can encode and pad them later. So this code will just do that. Secondly also for training, I need numpy arrays instead of just straight array. So I'm going to convert my training labels that I created into a numpy array like this. So that's all done. So next up is where I'm going to do my sentence encoding. So I've decided I'm going to do a 10,000-word vocab size. Of course you can change that. My embedding dimensions, which you'll see in a moment will be 16 dimensions. I'm going to make sure all of my reviews are 120 words long. So if they are shorter than that there'll be padded. If there longer than that they'll be truncated. I'm setting the truncation type to be post, so we'll cut off the back of the review and not the front, and then my outer vocabulary token will be OOV like this.
So now if I import my TensorFlow keras preprocessing tokenizer, and pad sequences is in sequence as before. I'll instantiate my tokenizer passing it my vocabulary size, which as I said here earlier on was 10,000. Of course you can change that. Then my outer vocabulary token, the tokenizer will then be fit on the training sentences, not the testing sentences just the training ones. If I want to look at the word index for the tokenizer, all have to do say tokenizer.word_index. I will then convert my sentences into sequences of numbers, with the number being the value and the word being the key that were taken out of the training sentences when I did fit on text, and that will give me now my list of integers per sentence. If I want to pad or truncate them I use pads sequences to do that. So each of my sentences is now a list of numbers. Again, those numbers are the values in a key value pair, where the key of course is the word. The pad sequences will ensure that they're all the same length, which in this case is 120 words or 120 numbers. There'll be padded out or truncated to suit. I'm then going to do the same with the testing sequences, and I'm going to pad them in the same way. Do note that the testing sequences are tokenized based on the word index that was learned from the training words. So you may find a lot more OOVs, in the testing sequence than you would have in the training sequence, because there'll be a lot of words that it hasn't encountered. But that's what makes it a good test, because later if you're going to try out a review, you want to be able to do it to see how it will do with words that the tokenizer or the neural network hasn't previously seen. So I'll now run this code. I'll create my sequences, my padded sequences, my testing sequences, my testing patterns. This will take a few moments. So let's now take a look at the neural network itself, and it's very simple. It's just a sequential. The top layer of this is going to be an embedding, the embedding is going to be my vocab size, the embedding dimensions that I wanted to use, I had specified 16. My input length for that is 120, which is the maximum length of the reviews. So the output of the embedding will then be flattened, that will then be passed into a dense layer, which is six neurons and then that will be passed to a final layer with a sigmoid activation and only one neuron, because I know I've only got two classes. I'm just going to do one neuron instead of two. I didn't need to hard encode. I'll just do one neuron and my activation function being a sigmoid, it will push it to zero or one respectively. I can then compile that and take a look at the summary. Here's the summary, it all looks good. Again, each of my sentences, 120 characters, my embedding has 16, and out of that the flattened thing we'll have 1,920 values. They get fed into the dense. They get fed into the output layer. So let's train it. So I'm going to set just for 10 epochs and I'm going to fit it. So it's training, it's correct, 25,000 samples and validating on 25,000 samples. Let's see it training. Our accuracy starts at 73 percent on the training set, 85 on validation. Training over time is going to go up nicely. We're most likely overfitting on this, because our accuracy is so high, but even that a validation accuracy is not bad. It's in the 80s.
So we can see even by epoch seven our accuracy up to a one. Our validation accuracy is still in the low 80s, 81, 82 percent. Pretty good, but this clear overfitting going on. So by the time I've reached my final epoch, my training accuracy was 100 percent, my validation accuracy at 83 percent. It's quite healthy but I'm sure we could do better. So now let's take a look at what we'll do to view this in the embedding projector. So first of all, I'm going to take the output of my embedding, which was modeled out layer zero, and we can see that there were 10,000 possible words and I had 16 dimensions. Here is where I'm going to iterate through that array to pull out the 16 dimensions, the values for the 16 dimensions per word and write that as out_V, which is my vectors.tsv. Then the actual word associated with that will be written to out_M, which is my meta.tsv. So if I run that, it we'll do its trick and if you're running in Colab this piece of code, will then allow me to just download those files. So it'll take a moment and they'll get downloaded. There they are, vecs.tsv and meta.tsv. So if I now come over to the embedding projector, we see its showing right now the Word2Vec 10K. So if I scroll down here and say load data, I'll choose file, I'll take the vecs.tsv. I'll choose file. I'll take the meta.tsv, then load. I click outside and now I see this. But if I spherize the data, you can see it's clustered like this. We do need to improve it a little bit but we can begin to see that the words have been clustered in both the positive and negative. So for example if I search for the word boring, we can see like the nearest neighbors for boring are things like stink or unlikeable, prom, unrealistic wooden, devoid, unwatchable, and proverbial. So if come over here we can see. These are bad words. These are words showing a negative looking review.
I can see, there's lots of words that have fun in them, some positive, some negative, like unfunny, dysfunction, funeral are quite negative. So let's try exciting. So now if I come over here we're beginning to see, hey there's a lot of words clustered around positive, movies that matching exciting, that type of thing. So we can see them over really on this left-hand side of the diagram. Again, I just maybe if I search for Oscar, nothing really associated with Oscar because it's such a unique word. We could just have all kinds of fun with it like that. What if I search for brilliant? Again we can begin to see like words clustering over on this side, but there's not a lot of words that became close to brilliant. In this case, guardian, Jeffrey, Kidman, Gershwin. So these are brilliant being used as an adjective. Some good stuff in there though. So hopefully this is a good example of how you can start mapping words into vector spaces, and how you can start looking at sentiment and even visualizing how your model has learned sentiment from these sets of words. In the next video, we're going to look at a simpler version of doing IMDb than this one where we're doing writing a lot less code, we're taking advantage of stuff that was available to us TenserFlow data services.
---------------------------------------------------------------
Хорошо, давайте посмотрим на код, который мы будем использовать в этом окружении. Итак, если вы собираетесь использовать это пособие, пожалуйста, убедитесь, что установлен Python3. Для этого идём сюда и выбираем пункт Change runtime type и проверяем, что там стоит Python 3. Я оставляю аппаратное ускорение с GPU, чтобы увеличить скорость расчётов. Если импортировать TensorFlow под псевдонимом tf, и вывести значение tf.__version__, то вы увидите версию TensorFlow. Если вы проходите курс спустя время, то она может быть и 2.0. Если она 2.0, вам не нужно активировать стремительное исполнение, но поскольку тут версия 1.13, я подключу стремительное исполнение. И если у вас не установлены наборы данных TensorFlow, эта строка установит их вам, но у меня они уже установлены. Итак, дальше я просто импортирую наборы данных TensorFlow под псевдонимом tfds и загружаю с помощью функции tfds.load набор imdb_reviews, что даёт мне наборы данных imdb и info. Я собираюсь использовать info в другом видео, здесь же мы его использовать не будем. А вот с набором imdb мы поработаем прямо сейчас. Дальше идёт код, где я извлекаю тренировочный и тестовый наборы данных в переменные train_data и test_data. Я создам списки для тренировочных фраз и меток, а также для тестовых фраз и меток, и скопирую сюда содержимое тензоров, чтобы затем их закодировать и выполнить выравнивание. Итак, данный код всё это делает. Во-вторых, для обучения мне нужны массивы numpy вместо простых массивов, так что я преобразую созданные training_labels в массив numpy, вот так. Готово. Дальше я закодирую мои предложения. Я решил, что мне хватит словаря размером в 10 000 слов. Разумеется, вы можете изменить размер. Моих эмбеддинги, как вы сейчас увидите, будут 16-мерными. Я хочу обеспечить, чтобы все рецензии были длиной в 120 слов. Если они окажутся короче, то будут дополнены. Если длиннее — обрезаны. Я устанавливаю тип обрезки 'post', так что обрезка будет с конца рецензии, а не с начала, а мой токен для слов вне словаря будет <OOV>, как здесь.
Я импортирую из TensorFlow токенизатор и pad_sequences, как и раньше. Я инициализирую токенизатор, передавая ему мой размер словаря, который, как я уже сказал, равен 10 000. Конечно, вы можете его изменить. А также передаю токен для слов вне словаря. Токенизатор обучается на тренировочных предложениях — не на тестовых, а только на тренировочных. Если я хочу посмотреть на список слов токенизатора, нужно вызвать tokenizer.word_index. Затем я конвертирую мои предложения в последовательности чисел, где числа — это значения, а слова — ключи, взятые из тренировочных предложений, когда я запустил fit_on_texts. И тогда я получаю для каждого предложения по списку целых чисел. Если я хочу дополнить или обрезать их, то вызываю для этого функцию pad_sequences. Итак, каждое из моих предложений теперь стало списком чисел. Повторюсь, эти числа — значения в парах ключ-значение, где ключ, разумеется, это само слово. pad_sequences сделает их все одинаковой длины, в данном случае, это 120 слов, или 120 чисел. Они будут дополнены или обрезаны, чтобы удовлетворить ограничению. Затем я сделаю то же самое с тестовыми последовательностями, точно также выравнивая их. Обратите внимание, что тестовые последовательности токенизируются с использованием словаря, построенного на тренировочных словах, так что в тестовых последовательностях может встречаться куда больше токенов <OOV>, чем было в тренировочных, т.к. здесь будет множество слов, которые там не встречались. Но так даже лучше для проверки, ведь если вы захотите проверить какое-нибудь ревью, то нужно смотреть, как всё будет работать со словами, которые токенизатор или нейронная сеть раньше не видели. Итак, я запускаю этот код. Он создаёт мои последовательности, выровненные последовательности, тестовые последовательности и тестовые выровненные последовательности. Это займёт некоторое время. И теперь можно посмотреть, что выходит, запустив этот кусок кода. Например, тут вы видите, что я взял мой обратный индекс слов, и могу декодировать рецензию, поглядев на числа для этой рецензии и обратив их в слова. Итак, берём ключ для этого значения, и обратный индекс слов меняет местами ключ и значение. Мы видим, что декодированная рецензия, то, что пойдёт на вход [нейросети], это: "Я смотрел этот фильм на True Movies*, [*британский бесплатный телеканал - прим. пер.] что автоматически настроило меня <слово не из словаря>" — а в изначальком тексте, как видите, встречаются заглавные буквы, знаки препинания: скобки и запятые, — а слово "скептически" в результате не попало в 1000 использованных. Итак, это просто удобный способ, какого рода данные мы скормим нейросети. Давайте посмотрим теперь на саму нейросеть. Она очень простая. Слои идут последоветельно (Sequential): верхний слой — эмбеддинг, он будет по размеру моего словаря, а нужную мне размерность векторов эмбеддинга я задал равной 16. Длина входных данных у меня 120 — это максимальная длина рецензии. Вывод эмбеддинга надо сделать одномерным, затем он попадает в полносвязный слой с шестью нейронами, а их выход передаётся в последний слой с сигмоидным активатором и всего одним нейроном, ведь у меня всего два класса. И я буду использовать один нейрон, а не два, чтобы не приходилось менять код. Я делаю лишь один нейрон, и мой активатор будет сигмоидой, он будет прижимать выходные значения к 0 или 1. Теперь можно скомпилировать сеть и посмотреть сводку. Вот она, всё выглядит хорошо. Ещё раз: каждое из моих предложений состоит из 120 символов, размерность эмбеддинга 16, из выхода эмбеддингов делаем массив одномерным, это будет 1920 значений. Они попадают в полносвязный слой, а потом в выходной слой. Давайте обучим сеть. Я установлю всего 10 эпох и запущу fit. Сеть обучается, тут всё верно: 25 000 образцов и валидация на 25 000 образцов. Давайте посмотрим, как сеть обучается. Наша точность изначально 73% на тренировочных данных и 85% на валидационных. Точность на тренировочных данных со временем хорошо растёт. Мы здесь, похоже, переобучаемся, потому что наша точность столь высока, но даже при этом валидационная точность неплоха. Она больше 80%.
И мы видим, что уже к седьмой эпохе наша точность достигла 1.0. Наша валидационная точность всё ещё чуть выше 80%, 81-82%. Неплохо, но сеть явно переобучается. Итак, по завершении последней эпохи тренировочная точность 100%, а валидационная точность 82.35%. Это довольно неплохое значение, но я уверен, что может быть лучше. Теперь давайте посмотрим, как посмотреть результат в Embedding Projector. Во-первых, я извлекаю выход со слоя эмбеддинга, этот слой в модели был с индексом 0. И мы видим, что было 10 000 возможных слов и 16 измерений. Здесь я прохожу в цикле по массиву, чтобы извлечь эти 16 измерений, т.е., значения этих 16 измерений для каждого слова, и записать их в файл (переменная out_v) с именем vecs.tsv. А также само слово, связанное с эмбеддингом, записывается в out_m — файл с именем meta.tsv. Итак, если я это запущу, если сделать такой приём, и запустить в Colab этот участок кода, то смогу подгрузить сюда эти файлы. Нужно немного подождать — и вот они скачались. Вот они, vesc.tsv и meta.tsv. Если перейти к Embedding Projector, мы видим, что он показывает 10 000 слов из Word2Vec. Если прокрутить вниз и нажать на кнопку загрузки данных (Load data), выбрать файл — я возьму vecs.tsv, и выбрать ещё файл, я возьму meta.tsv — то файлы подгружаются. Кликну за пределами диалога, мы увидим вот это. Но если я отмечу Sphereize data, вы увидите, что они группируются вот так. Нам ещё требуются улучшения, но уже становится заметно, что слова группируются — как позитивные, так и негативные. Например, если найти слово boring [скучный], то мы видим его ближайших соседей, для "скучный" это слова вроде "отвратительный" или "непривлекательный", "ученический", "нереалистичный", "деревянный", "пустое место", "невозможно смотреть", "пресловутый". А если я пойду сюда, то мы увидим, что это плохие слова. Это слова, указывающие на отрицательную рецензию.
И видно, что здесь есть множество слов, можно поразвлекаться, их изучая: некоторые положительные, некоторые отрицательные, например: "не смешно", "неполноценный", "похоронный" — довольно отрицательные. Давайте попробуем "восхитительно". Если я перейду сюда, мы увидим — ого, здесь множество слов, сгруппированных вокруг положительно оцениваемых фильмов, получивших оценку "восхитительно" и ей подобные. Мы можем осмотреть их на левой стороне диаграммы. И давайте я попробую поискать "Оскар". С ним особо ничего не связано, ведь Оскар — крайне редкое здесь слово. Можно всячески играться с этими данными в том же духе. Что, если я поищу "блестящий"? И снова мы видим, что слова собираются на этой стороне, но не так уж много слов близки к слову "блестящий". В данном случае, это Гардиан, Джеффри, Кидман, Гершвин. "Блестящий" используется как определение. Тут всякие хорошие вещи. Я надеюсь, это хороший пример того, как можно отображать слова в векторное пространство и начинать искать эмоции, и даже визуализировать то, как ваша модель учится узнавать эмоции по набору слов. В следующем видео мы посмотрим на более простой способ работы с IMDB, чем этот — там наш код станет компактнее, т.к. мы воспользуемся тем, что предоставляют нам возможности TensorFlow Data Services.

9(w2)-video7: Remember the sarcasm dataset? (17.MLg_3c)

So that was an example using the IMDB data set, where data is provided to you by the tfds API, which I hope you found helpful. Now I'd like to return to the sarcasm data set from last week, and let's look at building a classifier for that. We'll start with importing tensorflow and json, as well as the tokenizer and pad sequences from pre-processing. Now let's set up our hyper parameters; the vocabulary size, embedding dimensions, maximum length of sentences, and other stuff like the training size. This data set has about 27,000 records. So let's train on 20,000 and validate on the rest. The sarcasm data is stored at this URL, so you can download it to /tmp/sarcasm.json with this code. Now that you have the data set, you can open it and load it as an iterable with this code. You can create an array for sentences, and another for labels, and then iterate through the datastore, loading each headline as a sentence, and each is_sarcastic field, as your label.
---------------------------------------------------------------
Итак, это был пример использования набора данных IMDB, где вы брали данные с помощью интерфейса TFDS, который, надеюсь, вы нашли для себя полезным. Сейчас я бы хотел вернуться к набору данных прошлой недели, который был посвящён сарказму. Давайте посмотрим, как построить классификатор для него. Начнём с импорта tensorflow и json, а также токенизатора и pad_sequences из библиотеки предварительной обработки. Теперь установим гиперпараметры: размер словаря, размерность эмбеддинга, максимальную длину предложений, и прочее, например, размер обучающей выборки. В этом наборе данных есть около 27 000 записей. Так что давайте обучать на 20 000 и тестировать на остальных. Набор данных находится по этому адресу, вы можете скачать его в файл /tmp/sarcasm.json, запустив этот код. Теперь, когда у вас есть набор данных, можно открыть и загрузить его в массив с помощью данного кода. Вы можете создать один массив для предложений и другой для меток, а затем циклом пройти по данным из datastore, загружая каждый заголовок как предложение, и каждое значение поля is_sarcastic в качестве метки.

10(w2)-video8: Building a classifier for the sarcasm dataset (17.MLg_3c)

To split the corpus into training and validation sets, we'll use this code. To get the training set, you take array items from zero to the training size, and to get the testing set, you can go from training size to the end of the array with code like this. To get the training and testing labels, you'll use similar codes to slice the labels array. Now that we have training and test sets of sequences and labels, it's time to sequence them. To pad those sequences, you'll do that with this code. You start with a tokenizer, passing it the number of words you want to tokenize on and the desired out of vocabulary token. Then fit that on the training set by calling fit on texts, passing it the training sentences array. Then you can use text to sequences to create the training sequence, replacing the words with their tokens. Then you can pad the training sequences to the desired length or truncate if they're too long. Next, you'll do the same but with a test set. Now, we can create our neural network in the usual way. We'll compile it with binary cross entropy, as we're classifying to different classes. When we call a model's summary, we'll see that it looks like this, pretty much as we'd expect. It's pretty simple and embedding feeds into an average pooling, which then feeds our DNN. To train for 30 epochs, you pass in the padded data and labels. If you want to validate, you'll give the testing padded and labels to. After training for little while, you can plot the results. Here's the code for simple plot. We can see accuracy increase nicely as we trained and the validation accuracy was okay, but not great. What's interesting is the loss values on the right, the training loss fall, but the validation loss increased. Well, why might that be?
---------------------------------------------------------------
Чтобы разделить корпус на тренировочный и валидационный наборы, мы используем данный код. Чтобы получить тренировочный набор, возьмём элементы массива от 0 до training_size, а чтобы получить тестовый набор, берём начиная с training_size и до конца массива с помощью такого кода. Чтобы получить метки для тестового и тренировочного наборов данных, массив меток labels разделяется аналогично. Теперь у нас есть тренировочный и тестовый наборы предложений и меток, и пора превратить их в последовательности и выполнить выравнивание этих последовательностей, что делается вот этим кодом. Вы начинаете с токенизации: передаёте количество слов, которые нужно токенизировать, а также желаемый токен "нет в словаре". Затем обучаете токенизатор на тренировочном наборе, вызывая метод fit_on_texts и передавая ему массив тренировочных последовательностей. Затем вы используете text_to_sequences, чтобы создать тренировочные последовательности, заменяя слова их токенами. Затем можно дополнить тренировочные последовательности до желаемой длины — или обрезать слишком длинные. Потом вы делаете то же самое с тестовым набором. Теперь можно создать нейросеть, как обычно. Мы скомпилируем её с функцией потерь 'binary_crossentropy', т.к. мы классифицируем на два разных класса. Если вывести сводку по данной сети, то она будет выглядеть вот так. Этого мы и ожидали. Сеть довольно простая, и данные из эмбеддинга попадают в усредняющий слой, который потом передаёт данные в полносвязную нейросеть. Чтобы тренировать в течение 30 эпох, вы передаёте выровненные данные и метки к ним. Если вы хотите проверять метрики на тестовом наборе, то нужно также передать выровненные тестовые данные и их метки. Немного подождав окончания тренировки, можно вывести результаты на график. Вот код для построения простого графика. Мы видим, что точность во время обучения растёт как надо, а вот точность на валидационных данных хотя и неплоха, но далека от совершенства. Но что любопытно — так это график функции потерь справа. Функция потерь на тренировочных данных идёт вниз, а на валидационных — растёт. Почему бы это?

11(w2)-video9: Let’s talk about the loss (17.MLg_3c)

Think about loss in this context, as a confidence in the prediction. So while the number of accurate predictions increased over time, what was interesting was that the confidence per prediction effectively decreased. You may find this happening a lot with text data. So it's very important to keep an eye on it. One way to do this is to explore the differences as you tweak the hyperparameters. So for example, if you consider these changes, a decrease in vocabulary size, and taking shorter sentences, reducing the likelihood of padding, and then rerun, you may see results like this. Here, you can see that the loss has flattened out which looks good, but of course, your accuracy is not as high. Another tweak. Changing the number of dimensions using the embedding was also tried. Here, we can see that that had very little difference. Putting the hyperparameters as separate variables like this is a useful programming exercise, making it much easier for you to tweak and explore their impact on training. Keep working on them and see if you can find any combinations that give a 90 percent plus training accuracy without a cost of the lost function increasing sharply. In the next video, we'll also look at the impact of splitting our words into sub-tokens and how that might impact your training.
---------------------------------------------------------------
Функцию потерь здесь стоит рассматривать как надёжность предсказания. Если число точных предсказаний у нас увеличивалось с течением времени, то интересно при этом то, что надёжность отдельно взятых предсказаний при этом снижалась. Такое может очень часто наблюдаться для текстовых данных. Поэтому очень важно следить за надёжностью. Один из способов — изучать разницу в процессе подстройки гиперпараметров. Например, если взять такие изменения, как уменьшение размера словаря [было 10 000, стало 1000 - прим пер.] и сокращение длины предложений, [16 вместо 32 - прим.пер.] благодаря которому последовательности реже дополняются, — и снова запустить код, то результаты будут примерно такие. Видно, что функция потерь стала плоской, что хорошо. Но точность, разумеется, уже не так высока. Можно попробовать другое изменение: изменить размерность эмбеддинга. Здесь мы видим, что влияет оно очень слабо. Выносить гиперпараметры в отдельные переменные, как здесь, — практика, которой стоит придерживаться: так вам будет намного проще вносить поправки и исследовать их влияние на процесс тренировки. Ещё поупражняйтесь с этим, и посмотрите, получится ли у вас отыскать комбинацию, дающую точность более 90% на тренировочном наборе, не вызывая при этом резкого роста функции потерь. В следующем видео мы посмотрим, как разбиение слов на составные части скажется на процессе обучения.

12(w2)-Check out the code! (Lab 2): (17.MLg_3c)

Ungraded Lab: Training a binary classifier with the Sarcasm Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W2/ungraded_labs/C3_W2_Lab_2_sarcasm_classifier.ipynb

13(w2)-video10: Pre-tokenized datasets (17.MLg_3c)

Earlier this week, we looked at using TensorFlow Data Services, or TFDS to load the reviews from the IMDb dataset and perform classification on them. In that video, you loaded the raw text for the reviews, and tokenized them yourself. However, often with prepackaged datasets like these, some data scientists have done the work for you already, and the IMDb dataset is no exception. In this video, we'll take a look at a version of the IMDb dataset that has been pre-tokenized for you, but the tokenization is done on sub words. We'll use that to demonstrate how text classification can have some unique issues, namely that the sequence of words can be just as important as their existence.
---------------------------------------------------------------
Мы уже посмотрели на этой неделе, как использовать TensorFlow Data Services, или TFDS, чтобы загружать рецензии из набора данных IMDB и классифицировать их. В этом видео вы загрузите необработанный текст рецензий и токенизируете его самостоятельно. В случае подготовленных наборов данных, как эти, кто-то из специалистов по данным уже сделал за вас эту работу, и набор данных IMDB здесь не исключение. В этом видео мы рассмотрим другую версию набора данных IMDB, которую тоже токенизировали предварительно, но разбивку произвели по частям слов. Мы используем его, чтобы продемонстрировать, что в классификации текстов возможны свои особые нюансы. А именно, что последовательность слов может быть так же важна, как и их наличие.

14(w2)-TensorFlow datasets: (17.MLg_3c)

Please find here the datasets GitHub url.
https://github.com/tensorflow/datasets/tree/master/docs/catalog
For more information, please checkout the TensorFlow datasets documentation.
https://www.tensorflow.org/datasets/catalog/overview
---------------------------------------------------------------
Пожалуйста, найдите здесь URL-адрес GitHub наборов данных.
https://github.com/tensorflow/datasets/tree/master/docs/catalog
Для получения дополнительной информации ознакомьтесь с документацией по наборам данных TensorFlow.
https://www.tensorflow.org/datasets/catalog/overview

15(w2)-video11: Diving into the code (part 1) (17.MLg_3c)

So we'll start by looking at TensorFlow Datasets, you can find them at this URL. If you look at the IMDB reviews data-set, you'll see that there's a bunch of versions that you can use. These include,"plain_text" which we used in the last video,"bytes", where the text is encoded at byte level, and sub-word encoding which we'll look at in this video. You can now start using the imdb subwords dataset. We'll use the 8k version today. Getting access to your training and test data is then as easy as this. Next, if you want to access the sub words tokenizer, you can do it with this code. You can learn all about the sub-words texts encoder at this URL.
---------------------------------------------------------------
Итак, сначала заглянем в описание наборов данных из TensorFlow, он находится по этой ссылке. Если найти там набор imdb_reviews, то у него имеется несколько версий, доступных для использования. Сюда входят "plain_text" (плоский текст), который мы использовали в прошлом видео, а также "bytes", где текст закодирован побайтово, и набор, кодированный по частям слов, который мы рассмотрим в этом видео. Обратите внимание, что для кода, который я здесь покажу, нужно использовать TensorFlow 2.0, т.к. есть несколько несовместимостей с версией 1.x. Поэтому, если вы используете Colab, вам нужно сначала вывести версию TF. Если она 1.x, придётся сначала установить TensorFlow 2, как указано здесь. Обратите внимание, что с течением времени "-alpha0" нужно будет заменить на более поздние версии. Поэтому при любых трудностях советую вам обратиться к актуальному руководству по установке TensorFlow 2.0. Советую запустить эту строку ещё раз, чтобы убедиться, что теперь у вас версия 2, — прежде чем двинуться дальше. Особенно если вы используете Colab или Jupyter Notebook. Установив TensorFlow 2, можно начать использовать набор данных imdb с разбивкой слов на части. Сегодня мы используем версию 8k. Здесь показано, насколько просто получить тренировочный и тестовый наборы данных. А чтобы получить доступ к токенизатору по фрагментам слов, нужно выполнить данный код. Получить полную информацию о разбиении по частям слов можно по этой ссылке.

16(w2)-Subwords text encoder: (17.MLg_3c)

The documentation for the subword text encoder can be found here
https://www.tensorflow.org/datasets/api_docs/python/tfds/deprecated/text/SubwordTextEncoder---------------------------------------------------------------

17(w2)-video11: Diving into the code (part 2) (17.MLg_3c)

We have a pre-trained sub-words tokenizer now, so we can inspect its vocabulary by looking at its sub-words property. If we want to see how it encodes or decode strings, we can do so with this code. So we can encode simply by calling the encode method passing it the string. Similarly, decode by calling the decode method. We can see the results of the tokenization when we print out the encoded and decoded strings. If we want to see the tokens themselves, we can take each element and decode that, showing the value to token. Note that this is case sensitive and punctuation is maintained unlike the tokenizer we saw in the last video. You don't need to do anything with them yet, I just wanted to show you how sub-word tokenization works. So now, let's take a look at classifying IMDB with it. What the results are going to be? Here's the model. Again, it should look very familiar at this point. One thing to take into account though, is the shape of the vectors coming from the tokenizer through the embedding, and it's not easily flattened. So we'll use Global Average Pooling 1D instead.
Here's the output of the model summary. You can compile and train the model like this, it's pretty standard. You can graph the results with this code, and your graphs will probably look something like this. sub-word meanings are often nonsensical and it's only when we put them together in sequences that they have meaningful semantics. Thus, some way from learning from sequences would be a great way forward, and that's exactly what you're going to do next week with recurrent neural networks
---------------------------------------------------------------
Теперь у нас есть предобученный токенизатор по фрагментам слов, так что мы можем изучить его словарь, обратившись к его полю tokenizer.subwords. А посмотреть, как он кодирует или декодирует строки, можно с помощью данного кода. Для кодирования нужно просто вызвать метод encode, передав в него строку. Декодировать — аналогично, вызовом метода decode. Чтобы увидеть результат токенизации, выведем закодированную и декодированную строки. Чтобы увидеть сами токены, можно декодировать все элементы по очереди, выводя значения и их токены. Обратите внимание, что этот токенизатор чувствителен к регистру, и сохраняет знаки препинания, в отличие от того, который мы видели в предыдущем видео. Вам пока не надо ничего с ним делать, я просто хотел показать вам, как работает токенизация по частям слов. А теперь посмотрим, как работает классификация IMDB на его основе. Какими будут результаты? Вот модель. Опять же, она теперь должна выглядеть для вас знакомо. Но следует принять во внимание, что вектору, приходящему из токенизатора через эмбеддинг, не так просто придать одномерный вид. Так что мы используем GlobalAveragePooling1D вместо Flatten.
Здесь выведена сводная информация о модели. Можно скомпилировать и обучить модель, как здесь, это типовой код. Можно вывести результаты на график с помощью этого кода. И ваш график, вероятно, будет выглядеть примерно так. Части слов обычно не несут никакого смысла, и только когда мы составляем из них последовательности, они приобретают значение. А значит, некий способ обучаться на таких последовательностях стал бы большим шагом вперёд, и как раз этим мы и займёмся на следующей неделе, когда рассмотрим рекуррентные нейросети.

18(w2)-Check out the code! (Lab 3): (17.MLg_3c)

Ungraded Lab: Subword Tokenization with the IMDB Reviews Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W2/ungraded_labs/C3_W2_Lab_3_imdb_subwords.ipynb

19(w2)- Week 2 Quiz: (17.MLg_3c)

1) what is the name of the TensorFlow library containing common data that you can use to train and test neural networks?:
1. There is no library of common data sets, you have to use your own
2. TensorFlow Data
3. TesorFlow Data Libraries
4. TensorFlow Datasets (+)
2) How many reviews are there is the IMDB dataset and how are they split?:
1. 50,000 records, 80/20 train/test split
2. 60,000 records, 80/20 train/test split
3. 50,000 records, 50/50 train/test split (- +)
4. 60,000 records, 50/50 train/test split
3) How are the labels for the IMDB dataset encoded? in Python:
1. Reviews encoded as a number 0-1 (+)
2. Reviews encoded as a number 1-10
3. Reviews encoded as a boolean true/false
4. Reviews encoded as a number 1-5 (-)
4) What is the purpose of the embedding dimension?:
1. It is the number of dimensions required to encode every word in the corpus
2. It is the number of letters in the word, denoting the size of the encoding
3. it is the number of words to encode in the imbedding
4. It is the number of dimensions for the vector representing the word encoding (+)
5) When tokenizing a corpus, what does the num_words=n parameter do?:
1. It specifies the maximum number of words to be tokenized, and picks the most common 'n-1' words(+)
2. It specifies the maximum number of words to be tokenized, and picks the first 'n' words that were tokenized
3. It errors out if there are more than n distinct words iin the corpus
4. It specifies the maximum number of words to be tokenized, and stops tokenizing when it reaches n
6) To use word embeddings in TensorFlow, in a sequential layer, what is the name of the class?:
1. tf.keras.layers.Embed
2. tf.keras.layers.WordEmbedding
3. tf.keras.layers.Embedding (+)
4. tf.keras.layers.Word2Vector
7) IMDB Reviews are either positive of negative. What type of loss function should be used in this scenario?:
1. Adam
2. Binary Gradient descent
3. Categorical crossentropy
4. Binary crossentropy (+)
8) When using IMDB Sub Words Dataset, our results in classification were poor. Why?:
1. Our neural network didn't have enough layers
2. We didn't train long enough (-)
3. Sequence becomes much more important when dealing with subwords, but we're ignoring word positions (+)
4. The sub words make no sense, so can't be classified

20(w2)- Week 2 Wrap up: (17.MLg_3c)

Here are the key takeaways for this week:
- You looked at taking your tokenized words and passing them to an Embedding layer.
- Embeddings map your vocabulary to vectors in higher-dimensional space.
- The semantics of the words were learned when those words were labeled with similar meanings. For example, when looking at movie reviews, those movies with positive sentiment had the dimensionality of their words ending up pointing a particular way, and those with negative sentiment pointing in a different direction. From these, the words in future reviews could have their direction established and your model can infer the sentiment from it.
- You then looked at subword tokenization and saw that not only do the meanings of the words matter but also the sequence in which they are found.
Next week, you will:
-Look at other network architectures that you can use when building NLP models.
- Use Recurrent Neural Networks to take note of the sequence of your tokens.
- Use a convolutional layer to extract features from your model.
- Compare the performance of different architectures in building binary classifiers.
---------------------------------------------------------------
Here are the key takeaways for this week:
- You looked at taking your tokenized words and passing them to an Embedding layer.
- Embeddings map your vocabulary to vectors in higher-dimensional space.
- The semantics of the words were learned when those words were labeled with similar meanings. For example, when looking at movie reviews, those movies with positive sentiment had the dimensionality of their words ending up pointing a particular way, and those with negative sentiment pointing in a different direction. From these, the words in future reviews could have their direction established and your model can infer the sentiment from it.
- You then looked at subword tokenization and saw that not only do the meanings of the words matter but also the sequence in which they are found.
Next week, you will:
-Look at other network architectures that you can use when building NLP models.
- Use Recurrent Neural Networks to take note of the sequence of your tokens.
- Use a convolutional layer to extract features from your model.
- Compare the performance of different architectures in building binary classifiers.

21(w2)- Lecture Notes Week 2: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/natural-language-processing-tensorflow/ungradedLti/jF6xb/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License. DeepLearning.AI makes these slides available for educational purposes.
https://www.deeplearning.ai
ou may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see https://creativecommons.org/licenses/by-sa/2.0/legalcode

22(w2)- Programming Assignment: Diving deeper into the BBC News archive2: (17.MLg_3c)

C3W2_Assignment
Week 2: Diving deeper into the BBC News archive

NEXT week_3 (17.MLg_3c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3)Assessments Overdue (17.MLg_3c)

(Оценки просрочены)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video: 10 minutes
Self-study: 3h 16 min
Graded tasks (Tasks to be assessed): 2

(w3) Content (17.MLg_3c)

1. LSTM Long Short-Term Memory. LSTM (долгая краткосрочная память) является типом рекуррентной нейронной сети (RNN).
2. IMDB Subwords 8K with Single Layer LSTM
3. IMDB Subwords 8K with Multi Layer LSTM
4. GRU — Gated Recurrent Unit
5. Using Convolutional Neural Networks
6. IMDB Reviews with LSTM, GRU and Conv1D
7. Sarcasm with Bidirectional LSTM
8. Sarcasm with 1D Convolutional Layer

(w3) Introduction: (17.MLg_3c)

In the last couple of weeks you looked first at Tokenizing words to get numeric values from them, and then using Embeddings to group words of similar meaning depending on how they were labelled. This gave you a good, but rough, sentiment analysis -- words such as 'fun' and 'entertaining' might show up in a positive movie review, and 'boring' and 'dull' might show up in a negative one. But sentiment can also be determined by the sequence in which words appear. For example, you could have 'not fun', which of course is the opposite of 'fun'. This week you'll start digging into a variety of model formats that are used in training models to understand context in sequence!
---------------------------------------------------------------
За последние пару недель вы сначала посмотрели на токенизацию слов, чтобы получить из них числовые значения, а затем использовали вложения для группировки слов схожего значения в зависимости от того, как они были помечены. Это давало вам хороший, но грубый анализ настроений — такие слова, как «весело» и «развлекательный», могли появиться в положительном обзоре фильма, а «скучный» и «скучный» — в отрицательном. Но настроение также можно определить по последовательности, в которой появляются слова. Например, у вас может быть «не весело», что, конечно, противоположно «весело». На этой неделе вы начнете изучать различные форматы моделей, которые используются в обучающих моделях для последовательного понимания контекста!

1(w3)-video1: A conversation with Andrew Ng (17.MLg_3c)

Welcome back. In this video, you'll learn how to implement sequence models, in TensorFlow, and if you've heard of models like an RNN, or Recurrent Neural Network, this week we'll teach you how to implement that. It's important to really take words, and compute embeddings for them, but the relative ordering, the sequence of words matters too for the meaning of a sentence, and if you jumble the words around, that changes, or destroys the meaning of a sentence. Definitely, and so if you take just a very simple sentence, like my dog sat on my hat, and you swap the words dog, and hat, you're now changing from a sentence that has some kind of meaning, and some semantics, to a ridiculous sentence that has no meaning, right? My hat sat on my dog, unless you have a really smart hat, it doesn't really mean anything. So when we were doing classification based on embeddings, it was very nice that we had words with similar meanings, labels in a particular way, so that we could say okay, this is a positive review, and I got a bunch of vectors that are similar, this is a negative review, and I got these vectors in a similar way, but ordering those then gives us that whole extra layer of meaning that'll help us to understand the sentence rather than just a simple classification. So for a neural network, to take into account the ordering of the words, people now use specialized Neural Network Architectures, things like an RNN, or GIO, or LSTM, and you see what all these terms mean, and a little bit, in order for these Specialized Neural Networks to process natural language. Yeah. So like something like an RNN, it's really interesting that, the context is preserved from timestamp to timestamp, which can be really useful, but that might get lost in longer sentences, and that's why I really love LSTMs because LSTMs have that cell state, and the cell state are almost like a conveyor belts carrying contexts all the way down, for a long way down timestamp. I love that you have a favorite flavor on how sequence follow. I hold no shame, and keeping favorites. So then, in a really long sentence, like for example, I grew up in Ireland, so I went to school, and at school, they made me learn how to speak something. It's like you could say, okay the context from speak, means that it's a language, but you have to go all the way back to the beginning of the sentence to see that it's Ireland, and then in Ireland, I would learn how to speak. You speak Gaelic. Really badly. Since we learn to invent all of these things. Let's go on to the next video.
---------------------------------------------------------------
И снова здравствуйте. Из этого видео вы узнаете, как реализовать модели последовательностей в TensorFlow. И если вы слышали о таких моделях, как РНС, т.е., Рекуррентные Нейронные Сети, то на этой неделе мы научим вас, как их реализовывать. Важно брать сами слова и вычислять для них эмбеддинги, но и относительный порядок, последовательность слов — также имеет значение для смысла предложения. Если перемешать все слова, это изменит или уничтожит смысл предложения. Да, определённо, взять хоть простое предложение, скажем, "My dog sat on my hat" (Моя собака сидела на моей шляпе). Поменяйте местами слова dog и hat, и вы из предложения, у которого был какой-то смысл и определённое значение, получите абсурдное и бессмысленное предложение, верно? My hat sat on my dog (Моя шляпа сидела на моей собаке) Если только у вас нет действительно учёной шляпы, это на самом деле ничего не значит. Это как при классификации на основе эмбеддингов нам помогало то, что близкие по смыслу слова размечались таким образом, что можно было сказать: "Вот это — положительная рецензия", и получить набор похожих векторов, "А это — отрицательная рецензия" — и тоже получить подобные вектора. Но если выстроить слова по порядку, то это даст нам целый дополнительный слой значений, и поможет понять само предложение, не ограничиваясь простой классификацией. Итак, чтобы нейросеть могла принимать во внимание порядок слов, сейчас используют особую архитектуру нейросетей, такую, как РНС, или GIO, или LSTM, (вы скоро узнаете, что означают все эти термины) — чтобы специализированные нейросети могли обрабатывать естественный язык. Да, нечто вроде РНС, и здесь по-настоящему интересно, что контекст (вычислений) сохраняется от одной отметки времени до следующей, что может быть очень полезно, — но при длинных предложениях этот контекст [в РНС] может исчезать, и вот почему мне так нравятся LSTM: потому что в LSTM есть вектор состояний, и этот вектор состояний похож на ленту конвейера, которая всё время тащит этот контекст, сохраняя его долгое время. Мне нравится, что у вас есть любимый подход к работе с последовательностями. Мне не стыдно, что у меня есть любимчики. Итак, в действительно длинном предложении, например, "Я вырос в Ирландии, и там я ходил в школу, и в школе меня заставляли учиться говорить &lt;на чём-то&gt;." И тут можно было бы сказать: по контексту, "говорить" означает, что речь идёт о языке, но тут нужно вернуться далеко назад, к началу предложения, и увидеть, что это Ирландия, а на чём я должен был учиться говорить в Ирландии? Вы говорите на гэльском. Да! Но очень плохо. И чтобы обучать всему этому с нуля, давайте перейдём к следующему видео.

2(w3)-video2: Introduction (17.MLg_3c)

Last week, we looked at doing classification using texts and trying to train and understand positive and negative sentiment in movie reviews. We finished by looking at the effect of tokenizing words, and saw that our classifier failed to get any meaningful results. The main reason for this was that the context of words was hard to follow when the words were broken down into sub-words and the sequence in which the tokens for the sub-words appear becomes very important in understanding their meaning. Let's take a look at that now. The neural network is like a function that when you feed it in data and labels, it infers the rules from these, and then you can use those rules. So it could be seen as a function a little bit like this, you take the data and you take the labels, and you get the rules. But this doesn't take any kind of sequence into account. To understand why sequences can be important, consider this set of numbers. If you've never seen them before, they're called the Fibonacci sequence. So let's replace the actual values with variables such as n_0, n_1 and n_2, etc., to denote them. Then the sequence itself can be derived where a number is the sum of the two numbers before it. So 3 is 2 plus 1, 5 is 2 plus 3, 8 is 3 plus 5, etc. Our n_x equals n_x minus 1, plus n_x minus 2, where x is the position in the sequence. Visualized, it might also look like this, one and two feed into the first function and three comes out. Two gets carried over to the next, where it's fed in along with the three to give us a five. The three is carried on to the next where it's fed into the function along with the five to get an eight and so on. This is similar to the basic idea of a recurrent neural network or RNN, which is often drawn a little like this. You have your x as in input and your y as an output. But there's also an element that's fed into the function from a previous function. That becomes a little more clear when you chain them together like this, x_0 is fed into the function returning y_0. An output from the function is then fed into the next function, which gets fed into the function along with x_2 to get y_2, producing an output and continuing the sequence. As you can see, there's an element of x_0 fed all the way through the network, similar with x_1 and x_2 etc. This forms the basis of the recurrent neural network or RNN. I'm not going to go into detail and how they work, but you can learn much more about them at this course from Andrew.
---------------------------------------------------------------
На прошлой неделе мы посмотрели, как классифицировать тексты, и попробовали обучать и различать положительные и отрицательные эмоции в кинорецензиях. Мы остановились на том, как влияет разбиение слов на части, и увидели, что у нашего классификатора не выходит получить хоть сколько-нибудь значимые результаты. Главная причина была в том, что контекст слов трудно уловить, если разбивать их на составные части, и конкретная последовательность, в которой идут эти части, играет очень важную роль в понимании значения. Давайте посмотрим. Нейросеть похожа на функцию, в которую вы подаёте данные и метки, а она извлекает из них правила, и затем можно эти правила использовать. Так что её можно рассматривать как функцию примерно такого вида: вы берёте данные и метки, и получаете правила. Но здесь не учитываются никакие последовательности. Чтобы понять, почему может быть важна именно последовательность, рассмотрим этот набор чисел. Если вы никогда его раньше не видели, то он называется последовательностью Фибоначчи. Заменим его значения, на обозначающие их переменные n_0, n_1, n_2, и так далее. Тогда можно вывести, что последовательность состоит в том, что очередное число является суммой двух предыдущих. Так, 3 = 2 + 1, 5 = 2 + 3 8 = 3 + 5, и т. д. n_x = n_x-1 + n_x-2, n_x = n_x-1 + n_x-2, где x — позиция числа в последовательности. Можно также изобразить это в таком виде. 1 и 2 попадают на вход первой функции, и из неё выходит 3, 2 переходит на следующий слой, где попадает на вход вместе с 3, и даёт 5. 3 переходит на следующий слой, попадая на вход функции вместе с 5, чтобы получилось 8, и так далее. Всё это очень близко к сути рекуррентной нейросети, РНС, которую часто изображают в таком духе. У вас есть вход x и выход y. Но есть ещё элемент, который попадает на вход функции из предыдущей функции. Будет немного понятнее, если развернуть сеть таким образом: x_0 попадает на вход функции, которая возвращает y_0. Выход из этой функции попадает на вход следующей функции, результат которой попадает на вход вместе с x_2, чтобы получить y_2, снова давая выходное значение, и тем самым продолжая последовательность. Как видите, здесь результат от x_0 проходит через всю сеть, и то же самое для x_1, x_2, и так далее. Это и является основой рекуррентной нейросети, или РНС. Я не собираюсь вдаваться подробно в то, как они работают, но вы можете больше узнать об этом вот в этом курсе Эндрю.

3(w3)-Link to Andrew's sequence modeling course: (17.MLg_3c)

Here is the link to Andrew's course on sequence modeling.
https://www.coursera.org/lecture/nlp-sequence-models/deep-rnns-ehs0S
---------------------------------------------------------------

4(w3)-video3: LSTMs (17.MLg_3c)

There can be a limitation when approaching text classification in this way. Consider the following. Here's a sentence. Today has a beautiful blue. What do you think would come next? Probably sky. Right? Today has a beautiful blue sky. Why would you say that? Well, there's a big clue in the word blue. In a context like this, it's quite likely that when we're talking about a beautiful blue something, we mean a beautiful blue sky. So, the context word that helps us understand the next word is very close to the word that we're interested in. But, what about a sentence like this, I lived in Ireland so at school they made me learn how to speak something. How would you finish that sentence? Well, you might say Irish but you'd be much more accurate if you said, I lived in Ireland so at school they made me learn how to speak Gaelic. First of course, is the syntactic issue. Irish describes the people, Gaelic describes the language. But more importantly in the ML context is the key word that gives us the details about the language. That's the word Ireland, which appears much earlier in the sentence. So, if we're looking at a sequence of words we might lose that context. With that in mind an update to RNNs is called LSTM, long short - term memory has been created. In addition to the context being passed as it is in RNNs, LSTMs have an additional pipeline of contexts called cell state. This can pass through the network to impact it. This helps keep context from earlier tokens relevance in later ones so issues like the one that we just discussed can be avoided. Cell states can also be bidirectional. So later contexts can impact earlier ones as we'll see when we look at the code. The detail about LSTMs is beyond the scope of this course but you can learn more about them in this video from Andrew.
---------------------------------------------------------------
Когда мы строим классификацию текстов таким образом, то можем столкнуться с ограничением. Подумайте вот о чём. Пусть есть предложение: "Сегодня красивое голубое &lt;...&gt;." Что, по-вашему, идёт дальше? Возможно, небо. Верно? Сегодня красивое голубое небо. Почему вы так сказали? Ну, существенной подсказкой служит слово "голубое". В подобных контекстах весьма вероятно, что при упоминании чего-то красивого и голубого мы имеем в виду красивое голубое небо. Контекстуальное слово, которое помогает нам понять, каким должно быть следующее слово, здесь стоит рядом с нужным нам словом. Но что вы скажете о таком предложении: "Я жил в Ирландии, так что в школе меня заставляли учиться говорить &lt;...&gt;" Как можно завершить предложение? Можно было бы сказать "по-ирландски", но будет намного точнее сказать: "Я жил в Ирландии, так что в школе меня заставляли учиться говорить по-гэльски." Конечно, прежде всего, это вопрос синтаксиса. "Ирландский" описывает человека, а "гэльский" описывает язык. Но для машинного обучения важнее то, какое ключевое слово даёт нам ответ, каким должен быть язык. Это слово — "Ирландия", которое встречается в предложении намного раньше. И если смотреть на последовательность слов, то можно потерять этот контекст. С учётом этого и был создан улучшенный вариант РНС — сети LSTM, или "Долгая краткосрочная память" (Long Short-term Memory). В дополнение к контексту, который как и в РНС, передаётся в сеть, у LSTM есть дополнительный "конвейер" контекста называемый вектором состояний. Он передаётся по сети, влияя на её работу. Это помогает хранить контекст от более ранних токенов, значимый для более поздних, чтобы избежать проблем, которые мы только что обсудили. Вектор состояний также может быть двунаправленным. То есть, более поздний контекст может влиять на более ранний, как мы убедимся при изучении кода. Подробности устройства LSTM выходят за рамки этого курса, но вы можете больше узнать о них из этого видео Эндрю.

5(w3)-More info on LSTMs: (17.MLg_3c)

Please find here a link to more information on LSTMs (Long Short Term Memory cells) by Andrew.
https://www.coursera.org/lecture/nlp-sequence-models/long-short-term-memory-lstm-KXoay
---------------------------------------------------------------

6(w3)-video4: Implementing LSTMs in code (17.MLg_3c)

So let's now take a look at how to implement LSTMs in code. Here's my model where I've added the second layer as an LSTM. I use the tf.keras.layers.LSTM to do so. The parameter passed in is the number of outputs that I desire from that layer, in this case it's 64. If I wrap that with tf.keras.layers.Bidirectional, it will make my cell state go in both directions. You'll see this when you explore the model summary, which looks like this. We have our embedding and our bidirectional containing the LSTM, followed by the two dense layers. If you notice the output from the bidirectional is now a 128, even though we told our LSTM that we wanted 64, the bidirectional doubles this up to a 128. You can also stack LSTMs like any other keras layer by using code like this. But when you feed an LSTM into another one, you do have to put the return sequences equal true parameter into the first one. This ensures that the outputs of the LSTM match the desired inputs of the next one. The summary of the model will look like this. Let's look at the impact of using an LSTM on the model that we looked at in the last module, where we had subword tokens.
---------------------------------------------------------------
Теперь посмотрим, как реализовать LSTM в коде. Вот моя модель, в которую я добавил вторым слоем LSTM. Для этого я использую keras.layers.LSTM. Туда передаётся параметр, который обозначает нужное число выходов из слоя, здесь это 64. Если обернуть этот слой в tf.keras.layers.Bidirectional, это заставляет мой вектор состояний передаваться в обе стороны. Это будет отражено в сводке о модели, которая выглядит вот так. У нас есть слой эмбеддинга и двунаправленный слой LSTM, за которым следуют два полносвязных слоя. Если вы заметили, выход из двунаправленного слоя сейчас имеет размерность 128, хотя мы и указали, что на выходе из LSTM хотим размерность 64. Двунаправленность удваивает его до 128. Слои LSTM можно выстраивать друг за другом, как и любые другие слои в keras, с помощью подобного кода. Но когда вы направляете выход одного LSTM слоя в другой, нужно передать параметр return_sequences=True в первый из них. Тем самым обеспечивается соответствие размерности выхода из LSTM-слоя входному размеру следующего слоя. Сводка о модели будет выглядеть примерно так. Давайте посмотрим, как использование LSTM скажется на модели, которую мы разбирали в прошлом модуле, когда разбивали слова на части.

7(w3)-Check out the code! (Lab 1 & Lab 2): (17.MLg_3c)

We've created a number of notebooks for you to explore the different types of sequence models.
Spend some time going through these to see how they work, and what the impact of different layer types have on training for classification.
IMDB Subwords 8K with Single Layer LSTM
Ungraded Lab: Single Layer LSTM
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_1_single_layer_LSTM.ipynb
IMDB Subwords 8K with Multi Layer LSTM
Ungraded Lab: Multiple LSTMs
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_2_multiple_layer_LSTM.ipynb
---------------------------------------------------------------

8(w3)-video5: Accuracy and loss (17.MLg_3c)

Here's the comparison of accuracies between the one layer LSTM and the two layer one over 10 epochs. There's not much of a difference except the nosedive and the validation accuracy. But notice how the training curve is smoother. I found from training networks that jaggedness can be an indication that your model needs improvement, and the single LSTM that you can see here is not the smoothest. If you look at loss, over the first 10 epochs, we can see similar results. But look what happens when we increase to 50 epochs training. Our one layer LSTM, while climbing in accuracy, is also prone to some pretty sharp dips. The final result might be good, but those dips makes me suspicious about the overall accuracy of the model. Our two layer one looks much smoother, and as such makes me much more confident in its results. Note also the validation accuracy. Considering it levels out at about 80 percent, it's not bad given that the training set and the test set were both 25,000 reviews. But we're using 8,000 sub-words taken only from the training set. So there would be many tokens in the test sets that would be out of vocabulary. Yet despite that, we are still at about 80 percent accuracy. Our loss results are similar with the two layer having a much smoother curve. The loss is increasing epoch by epoch. So that's worth monitoring to see if it flattens out in later epochs as would be desired. I hope this was a good introduction into how RNNs and LSTMs can help you with text classification. Their inherent sequencing is great for predicting unseen text if you want to generate some, and we'll see that next week. But first, I'd like to explore some other RNN types, and you'll see those in the next video.
---------------------------------------------------------------
Вот сравнение точностей между однослойной и двухслойной LSTM в течение 10 эпох. Разница не такая большая, за исключением того, что валидационная точность (первой) пикирует в конце. Но обратите внимание, что кривая обучения более гладкая. Обучая нейросети, я узнал, что её зазубренность может быть признаком того, что модель нуждается в улучшениях. И у однослойной LSTM, как видите, кривая не самая гладкая. Если взглянуть на график функции потерь в течение первых 10 эпох, вы увидите похожие результаты. Но посмотрите, что происходит, когда мы продляем обучение до 50 эпох. Наша однослойная LSTM, хотя её точность и растёт, подвержена при этом резким провалам. Конечный результат, может, и хорош, но эти провалы порождают у меня подозрения о точности модели в целом. Кривая двухслойной модели выглядит намного более гладкой, и внушает мне куда больше уверенности в результате. Обратите внимание также на валидационную точность и на то, что она выравнивается на уровне порядка 80%. Не так уж плохо, если учесть, что и тренировочный набор, и тестовый — состояли из 25 000 рецензий, но мы использовали 8000 различных частей слов, взятых только из тренировочного набора. Так что в тестовом наборе может быть много токенов, не попавших в словарь. И несмотря на это, мы всё равно достигли точности порядка 80%. Графики функции потерь похожи, и двухслойная сеть опять имеет намного более гладкую кривую. Величина потерь растёт эпоха за эпохой. За этим стоит следить, чтобы увидеть, не выравнивается ли график в более поздних эпохах, что было бы желательно. Надеюсь, это послужило хорошим введением в то, как РНС и LSTM помогают классифицировать тексты. Присущая им способность работать с последовательностями очень хороша для предсказывания ещё не виденного текста, когда нужно сгенерировать новый текст, в чём мы убедимся на следующей неделе. А пока я бы хотел разобрать некоторые другие разновидности РНС, и вы увидите их в следующем видео.

9(w3)-video6: A word from Laurence (17.MLg_3c)

In the last video we saw LSTMs and how they work with cell state to help keep context in a way that helps with understanding language. Well, words that aren't immediate neighbors can affect each other's context.
In this video, you'll see some other options of RNN including convolutions, Gated Recurrent Units also called GRUs, and more on how you can write the code for them. You'll investigate the impact that they have on training. I'm not going to go into depth on how they work, and that information is available in the deep learning specialization from Andrew. So do check it out there.
---------------------------------------------------------------
В прошлом видео мы посмотрели на LSTM и на то, как они работают с вектором состояния, чтобы сохранять контекст так, чтобы это помогало нам понимать язык. Слова, которые не стоят непосредственно рядом, могут влиять на контекст друг друга.
В этом видео вы увидите некоторые другие возможности РНС, включая свёртки, управляемые рекуррентные блоки (УРБ) [GRU — Gated Recurrent Unit - прим. пер.] и другие. А также как использовать их в своём коде. Вы изучите, как они влияют на обучение. Я не собираюсь подробно излагать механизм их работы, эта информация доступна в специализации Эндрю "Глубокое обучение". Так что можете посмотреть там.

10(w3)-video7: Looking into the code (17.MLg_3c)

So let's start with this basic neural network. It has an embedding taking my vocab size, embedding dimensions, and input length as usual. The output from the embedding is averaged and then fed into a dense neural network. But we can experiment with the layers that bridge the embedding and the dense by removing the pooling from here, and replacing them with an LSTM like this. If I train using the sarcasm data-set with these, when just using the pooling I quickly got close to 85 percent accuracy and then it flattened out there. The validation set was a little less accurate, but the curves we're quite in sync.
On the other hand, when using LSTM, I reached 85 percent accuracy really quickly and continued climbing towards about 97.5 percent accuracy within 50 epochs. The validation set dropped slowly, but it was still close to the same value as the non- LSTM version. Still the drop indicates that there's some over fitting going on here. So a bit of tweaking to the LSTM should help fix that. Similarly, the loss values from my non-LSTM one got to healthy state quite quickly and then flattened out. Whereas with the LSTM, the training loss drop nicely, but the validation one increased as I continue training. Again, this shows some over fitting in the LSTM network. While the accuracy of the prediction increased, the confidence in it decreased. So you should be careful to adjust your training parameters when you use different network types, it's not just a straight drop-in like I did here.
---------------------------------------------------------------
Итак, начнём с этой базовой нейросети. В ней есть слой эмбеддинга с параметрами, описывающими размер словаря, размерность эмбеддингов и длина входной последовательности, как обычно. Выход из эмбеддинга разворачивается в одномерный массив, усредняется и поступает на вход полносвязной нейросети. Здесь можно поэкспериментировать со слоями, которые связывают эмбеддинг и плотный слой, удалив отсюда разворачивание и усреднение и заменив их на LSTM, как здесь. Обучая на данных, посвящённых сарказму, и используя только усреднение и разворачивание эмбеддингов, я быстро подошёл к 85% точности, но потом она вышла на плато. Точность на валидационном наборе была несколько меньше, но кривые шли довольно согласованно. С другой стороны, при использовании LSTM я очень быстро достиг 85% точности, и продолжал наращивать её вплоть до 97.5% после 50 эпох. Точность на валидационном наборе медленно падала, но оставалась достаточно близкой к показателям версии без LSTM. Тем не менее, это падение указывает на то, что тут имеет место переобучение. Так что небольшая подстройка параметров LSTM должна это исправить. Аналогичным образом, значение функции потерь моей версии без LSTM довольно быстро достигло хороших показателей, а затем перестало снижаться. В то время как LSTM успешно снижала потери на тренировочном наборе, но на валидационном они росли по мере продолжения обучения. Повторю, что это признак того, что LSTM-сеть переобучается. И хотя точность предсказания увеличилась, уверенность в нём уменьшилась. Так что нужно внимательно подбирать параметры обучения при использовании сетей разных типов. Нельзя просто так взять, и совместить их, как я поступил здесь.

11(w3)-video8: Using a convolutional network (17.MLg_3c)

Another type of layer that you can use is a convolution, in a very similar way to what you did with images. The code to use a convolutional on network is here. It's very similar to what you had before. You specify the number of convolutions that you want to learn, their size, and their activation function. The effect of this will then be the same. Now words will be grouped into the size of the filter in this case 5. And convolutions will learned that can map the word classification to the desired output. If we train with the convolutions now, we will see that our accuracy does even better than before with close to about 100% on training and around 80% on validation. But as before, our loss increases in the validation set, indicating potential overfilling. As I have a super simple network here, it's not surprising, and it will take some experimentation with different combinations of convolutional layers to improve on this. If we go back to the model and explore the parameters, we'll see that we have 128 filters each for 5 words. And an exploration of the model will show these dimensions. As the size of the input was 120 words, and a filter that is 5 words long will shave off 2 words from the front and back, leaving us with 116. The 128 filters that we specified will show up here as part of the convolutional layer.
---------------------------------------------------------------
Ещё один тип слоёв, который здесь можно использовать — это свёрточный, его применение похоже на то, как было с изображениями. На экране код использования этого слоя в нейросети. Всё очень похоже на то, что было раньше: задаёте количество свёрток, которые вы хотите обучать, их размер и функцию активации. Результат тоже будет прежним. Теперь слова будут сводиться в группы, их равен размеру фильтра — здесь это 5. И свёртки будут учиться превращать классифицируемые слова в желаемые выходные значения. Если теперь обучить свёртку, то мы увидим, что точность стала даже лучше, чем раньше, она близка к 100% на тренировочном наборе и около 80% на валидационном. Но, как и раньше, на валидационном наборе наша функция потерь растёт, сигнализируя о потенциальном переобучении. И т.к. у меня крайне простая сеть, то в этом нет ничего удивительного, и потребуется ряд экспериментов с различными комбинациями свёрточных слоёв, чтобы добиться здесь улучшения. Если мы вернёмся к модели и исследуем параметры, то увидим, что у нас есть 128 фильтров, каждый на 5 слов. А если заглянуть в модель, то размерности будут следующими. Поскольку размер входа 120 слов, а фильтру нужно 5 слов, он отрежет по 2 слова в начале и в конце, оставив нам 116. 128 фильтров, которые мы указали, можно увидеть здесь, в составе свёрточного слоя.

12(w3)-Check out the code! (Lab 3): (17.MLg_3c)

Spend some time going through this notebook to see how it works.
IMDB Subwords 8K with 1D Convolutional Layer
Ungraded Lab: Using Convolutional Neural Networks
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_3_Conv1D.ipynb

13(w3)-video9: Going back to the IMDB dataset (17.MLg_3c)

So now that we've seen these, let's go back to the IMDB dataset that we used earlier in this course. Here, I'll just use an embedding that I flattened before it goes into the dense. My model will look like this, with a 171,533 parameters, and the performance will be like this. It's nice accuracy, but clear overfitting but it only takes about five seconds per epoch to train. If I change this to use an LSTM, it will take about 43 seconds per epoch. The accuracy is better, but there's still some overfitting.
If I try a GRU layer instead, with a GRU being a different type of RNN, and I make it bidirectional, my network will have a 169,997 parameters. My training time will fall to 20 seconds per epoch, and my accuracy is again very good on training, and not too bad on validation but again, showing some overfitting. With a convolutional network, I'll have a 171,149 parameters and it only takes about six seconds per epoch to get me close to 100 percent accuracy on training, and about 83 percent on validation, but again with overfitting.
---------------------------------------------------------------
Посмотрев на свёртки, давайте вернёмся к набору данных IMDB, который мы уже использовали в этом курсе. Здесь я использую просто эмбеддинг, который я развернул в одномерный массив перед передачей в полносвязный слой. Моя модель будет выглядеть так, с 171 533 параметрами. И показатели работы будет такими. Точность тут хорошая, но переобучение очевидно. Зато обучение одной эпохи занимает всего 5 секунд. Если я изменю сеть на LSTM, в ней будет только 30 129 параметров, но на одну эпоху обучения уйдёт примерно 43 секунды. Точность лучше, но сеть всё ещё переобучается. Если я попробую взамен LSTM слой УРБ, где УРБ — ещё одна разновидность РНС, и сделаю этот слой двунаправленным, в моей сети будет 169 997 параметров. Время обучения сократится до 20 секунд на эпоху, и точность снова будет очень хорошей на тренировочном наборе и неплохой на валидационном, но снова будет некоторое переобучение. Со свёрточной сетью в сети будет 171 149 параметров, а обучение займёт лишь 6 секунд на эпоху, и точность приблизится к 100% на тренировочном наборе и около 83 процентов на валидационном. Но переобучение будет и здесь.

14(w3)-Check out the code! (Lab 4): (17.MLg_3c)

Spend some time going through this notebook to see how it works and what the impact of different layer types have on training for classification.
IMDB Reviews with LSTM, GRU and Conv1D
Ungraded Lab: Building Models for the IMDB Reviews Dataset
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_4_imdb_reviews_with_GRU_LSTM_Conv1D.ipynb
---------------------------------------------------------------

15(w3)-video10: Tips from Laurence (17.MLg_3c)

Before you go onto the next unit, I have created some CO-LABS with each of these options. Try them out for yourself, check on the time, check on the results, and see what techniques you can figure out to avoid some of the overfitting. Remember that with text, you'll probably get a bit more overfitting than you would have done with images. Not least because you'll almost always have out of vocabulary words in the validation data set. That is words in the validation dataset that weren't present in the training, naturally leading to overfitting. These words can't be classified and, of course, you're going to have these overfitting issues, but see what you can do to avoid them.
---------------------------------------------------------------
Прежде чем вы перейдёте к следующему модулю, хочу сказать, что сделал несколько блокнотов в Colab, для каждого из вариантов. Попробуйте их самостоятельно, проверьте время обучения и результаты, попробуйте выяснить, какие приёмы помогут вам избежать переобучения. Помните, что в случае текста переобучение у вас будет проявляться сильнее, чем при работе с изображениями. Не в последнюю очередь, из-за того, что у вас почти всегда в валидационном наборе будут слова не из словаря. Это слова валидационного набора, которых не было в тренировочном, что, естественно, ведёт к переобучению. Эти слова нельзя классифицировать, и, конечно, у вас будут возникать проблемы с переобучением, но попробуйте с ними справиться.

16(w3)-Exploring different sequence models (Lab 5 & Lab 6): (17.MLg_3c)

We've created a couple of notebooks for you to explore the different types of sequence models for Sarcasm Detection.
Spend some time going through these to see how they work, and what the impact of different layer types have on training for classification.
Sarcasm with Bidirectional LSTM
Ungraded Lab: Training a Sarcasm Detection Model using Bidirectional LSTMs
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_5_sarcasm_with_bi_LSTM.ipynb
Sarcasm with 1D Convolutional Layer
Ungraded Lab: Training a Sarcasm Detection Model using a Convolution Layer
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W3/ungraded_labs/C3_W3_Lab_6_sarcasm_with_1D_convolutional.ipynb
---------------------------------------------------------------

17(w3)- Week 3 Quiz: (17.MLg_3c)

1) Why does sequence make a large difference when determining semantics of language?:
1. It doesn't
2. Because the order in which words appear dictate their impact on the meaning of the sentence (+)
3. Because the order in which words appear dictate their meaning
4. Because the order of words doesn't matter
2) How do Recurrent Neural Networks help you understand the impact of sequence on meaning?:
1. They don't
2. They shuffle the words evenly
3. They carry meaning from one cell to the next (+)
4. They look at the whole sentence at a time
3)How does an LSTM help understand meaning when words that qualify each other aren't necessarily beside each other in a sentence?:
1. They shuffle the words randomly
2. They load all words into a cell state
3. They don't
4. Values from earlier words can be carried to late ones via a cell state (+)
4) What keras layer type allows LSTMs to look forward and backward in a sentence?:
1. Unilateral
2. Bothdirection
3. Bilateral
4. Bidirectional (+)
5) What's the output shape of a bidirectional LSTM laery with 64 units?:
1. (128,1)
2. (None, 128) (- +)
3. (128, None)
4. (None, 64)
6) When stacking LSTMs, how do you instruct an LSTM to feed the next one in the sequence?:
1. Ensure that return_sequences is set to True on all units
2. Ensure that return_sequences is set to True only on units that feed to another LSTM (+)
3. Do nothing, TensorFlow handles this automatically
4. Ensure that they have the same number of units
7) If a sentence has 120 tokens in it, and a Conv1D with 128 filters with a Kernal size of 5 is passed over it, what's the output shape?:
1. (None, 120, 124)
2. (None, 120, 128)
3. (None, 116, 124)
4. (None, 116, 128) (+)
8) What's the best way to avoid overfitting in NLP datasets?:
1. Use LSTMs
2. Use GRUs
3. Use Conv1D
4. None of the above (+)

18(w3)- Week 3 Wrap up: (17.MLg_3c)

You’ve been experimenting with NLP for text classification over the last few weeks. Next week, you’ll switch gears and take a look at using the tools that you’ve learned to predict text, which ultimately means you can create text. By learning sequences of words, you can predict the most common word that comes next in the sequence. Thus when starting from a new sequence of words, you can create a model that builds on them. You’ll take different training sets -- like traditional Irish songs, or Shakespeare poetry, and learn how to create new sets of words using their embeddings!
---------------------------------------------------------------
Последние несколько недель вы экспериментировали с НЛП для классификации текстов. На следующей неделе вы переключитесь и взглянете на использование инструментов, которые вы изучили, для прогнозирования текста, что в конечном итоге означает, что вы можете создавать текст. Изучая последовательности слов, вы можете предсказать наиболее распространенное слово, которое будет следующим в последовательности. Таким образом, начиная с новой последовательности слов, вы можете создать модель, основанную на них. Вы возьмете различные обучающие наборы — например, традиционные ирландские песни или поэзию Шекспира, — и научитесь создавать новые наборы слов, используя их встраивания!

19(w3)- Lecture Notes Week 3: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

20(w3)- Programming Assignment: Exploring overfitting in NLP: (17.MLg_3c)

You have not submitted. You must earn 80/100 points to pass.
Deadline
The assignment was due on Jun 19, 9:59 AM EEST
You can still pass this assignment before the course ends.
C3W3_Assignment
Week 3: Exploring Overfitting in NLP

NEXT week_4 (17.MLg_3c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w4)Sequence models and literature (17.MLg_3c)

(Модели последовательности и литература)
(Natural Language Processing in TensorFlow)
---------------------------------------------------------------
Video:24 minutes
Self-study: 1h 26 min
Graded tasks (Tasks to be assessed): 2

(w4) Content (17.MLg_3c)

1. 2. 3.4.5.6.7.8.

(w4) Introduction: (17.MLg_3c)

Taking everything that you've learned in training a neural network based on NLP, we thought it might be a bit of fun to turn the tables away from classification and use your knowledge for prediction. Given a body of words, you could conceivably predict the word most likely to follow a given word or phrase, and once you've done that, to do it again, and again. With that in mind, this week you'll build a poetry generator. It's trained with the lyrics from traditional Irish songs, and can be used to produce beautiful-sounding verse of it's own!
---------------------------------------------------------------
Принимая во внимание все, что вы узнали при обучении нейронной сети на основе НЛП, мы подумали, что может быть немного забавно отвернуть таблицы от классификации и использовать свои знания для прогнозирования. Имея совокупность слов, вы могли бы предсказать слово, которое с наибольшей вероятностью будет следовать за данным словом или фразой, и, сделав это, повторять это снова и снова. Имея это в виду, на этой неделе вы создадите генератор стихов. Он обучен текстам традиционных ирландских песен и может быть использован для создания собственных красиво звучащих стихов!

1(w4)-video1: A conversation with Andrew Ng (17.MLg_3c)

Welcome back. One of the most fun applications of sequence models, is that they can read the body of text, so train on the certain body of text, and then generate or synthesize new texts, that sounds like it was written by similar author or set of authors. It's like, so one of the things that we're going to do in this week. In the courses, we're going to take a body of work from Shakespeare, and Shakespeare as a medieval English author, and so he wrote in a different style of English than we're used to reading, and it makes for a really interesting exercise in text generation, because if you're not familiar with like Shakespearean language and how it is done, then the language is actually generated by the neural network, will probably look a lot like the original one, probably, if you lived in the 1600's when Shakespeare was around, you'd be able to identify as being generated by a neural network, but for us now with this slightly different version of England, it actually makes for a really fun scenario. There's a really fun application in neural network, and one of my favorite teachers in high school, was actually my English teacher that made me memorize a lot of Shakespeare. I really wonder what she would think of this. Yes, I had exactly the same. I played Henry the fourth in high school. So I even, I know you all and well awhile uphold this unyoked humor of your idleness Hey, I even remember. I can't top that. So to do all this fun stuff yourself, let's go into this week's videos.
---------------------------------------------------------------
Добро пожаловать. Одно из наиболее занимательных применений последовательных моделей — это то, что они могут прочитать корпус текстов, обучиться на этих конкретных текстах? и потом генерировать, или синтезировать, новые тексты, которые будут выглядеть так, словно их написал тот же автор, или несколько авторов. И это одна из тех возможностей, которыми мы будем заниматься на этой неделе. В курсе мы возьмём собрание текстов Шекспира. А Шекспир — средневековый английский автор, и он писал в стиле, отличном от того английского языка, который мы привыкли читать, и это делает упражнение по генерированию текстов особенно интересным, ведь если вы незнакомы с языком Шекспира, с тем, как он устроен, то тот язык, который сгенерирует нейросеть, возможно, будет похож на оригинал. Но если бы вы жили в 1600-е годы, когда творил Шекспир, то, возможно, вы смогли бы определить, что этот текст сгенерирован нейросетью. Но в наши дни этот язык — чуть иная версия английского, и это действительно интересный сценарий. Это действительно занимательное применение нейросетей. Одним из моих любимых учителей в старшей школе была учитель английского, который заставил меня выучить многое из Шекспира, и хотелось бы мне знать, что бы она обо всём этом подумала. Да, у меня та же история. Я в старшей школе играл Генриха IV. Я даже... "Я всем вам знаю цену, но пока Потворщик первый вашим безобразиям." Я даже помню. Я так не смогу. Итак, чтобы научиться делать все эти занимательные вещи, — переходите к следующему видео.

2(w4)-video2: Introduction (17.MLg_3c)

We've seen classification of text over the last few lessons. But what about if we want to generate new text. Now this might sound like new unbroken ground, but when you think about it, you've actually covered everything that you need to do this already. Instead of generating new text, how about thinking about it as a prediction problem. Remember when for example you had a bunch of pixels for a picture, and you trained a neural network to classify what those pixels were, and it would predict the contents of the image, like maybe a fashion item, or a piece of handwriting. Well, text prediction is very similar. We can get a body of texts, extract the full vocabulary from it, and then create datasets from that, where we make it phrase the Xs and the next word in that phrase to be the Ys. For example, consider the phrase, Twinkle, Twinkle, Little, Star. What if we were to create training data where the Xs are Twinkle, Twinkle, Little, and the Y is star. Then, whenever neural network sees the words Twinkle, Twinkle, Little, the predicted next word would be star. Thus given enough words in a corpus with a neural network trained on each of the phrases in that corpus, and the predicted next word, we can come up with some pretty sophisticated text generation and this week, you'll look at coding that.
---------------------------------------------------------------
Последние несколько уроков мы имели дело с классификацией текстов. Но что, если мы захотим сгенерировать новый текст? Это может выглядеть как новое непаханое поле. Но если поразмыслить об этом, то мы уже изучили всё, что требуется, чтобы это сделать. Что, если посмотреть на это не как на порождение нового текста, а как на задачу предсказания? Вспомните, как, к примеру, вы брали пиксели, составлявшие картинку, и обучали нейросеть определять, что на этих пикселях, и она предсказывала, что на изображении: скажем, предмет одежды или письменные знаки. Предсказание текста очень похоже. У нас есть некоторый корпус текстов, мы строим по нему полный словарь, а затем создаём из него набор данных, где фразы будут за X, а следующее слово во фразе — за Y. Возьмём, например, фразу: "Чижик-пыжик, где ты был?" Что, если построить тренировочный набор, где X — это "Чижик-пыжик, где ты", а Y — "был"? И когда нейросеть увидит слова "Чижик-пыжик, где ты", она предскажет, что следующее слово — "был". Если у нас в корпусе достаточно много слов, и нейросеть обучена на каждой фразе из этого корпуса, предсказывая следующее слово, — то у нас может выйти довольно продвинутый генератор текстов. И на этой неделе вы посмотрите, как его закодировать.

3(w4)-video3: Looking into the code (17.MLg_3c)

So let's start with a simple example. I've taken a traditional Irish song and here's the first few words of it, and here's the beginning of the code to process it. In this case to keep things simple, I put the entire song into a single string. You can see that string here and I've denoted line breaks with \n. Then, by calling the split function on \n, I can create a Python list of sentences from the data and I'll convert all of that to lowercase. Using the tokenizer, I can then call fit_on_texts to this corpus of work and it will create the dictionary of words and the overall corpus. This is a key value pair with the key being the word and the value being the token for that word. We can find the total number of words in the corpus, by getting the length of its word index. We'll add one to this, to consider outer vocabulary words.
---------------------------------------------------------------
Давайте начнём с простого примера. Я взял ирландскую народную песню, и вот первые её слова. А вот первая часть кода для её обработки. В этом случае, чтобы не усложнять, я поместил всю песню в одну строку. Вот эта строка, где я обозначил переводы строк \n Вызовом функции split с параметром "\n" я могу сформировать в Python список предложений по этим данным, переведя их в нижний регистр. Используя токенизатор, я могу вызвать на этом корпусе fit_on_texts, и это даст мне словарь всех слов данного корпуса. Это пары ключ-значение, где ключом будет слово, а значением — его токен. Можно узнать общее число слов в корпусе, взяв длину словаря. Добавим к ней единицу, чтобы учесть токен для слов вне словаря.

4(w4)-video4: Preparing the training data (17.MLg_3c)

So now, let's look at the code to take this corpus and turn it into training data. Here's the beginning, I will unpack this line by line. First of all, our training x's will be called input sequences, and this will be a Python list. Then for each line in the corpus, we'll generate a token list using the tokenizers, texts to sequences method. This will convert a line of text like, "In the he town of Athy one Jeremy Lanigan," into a list of the tokens representing the words. Then we'll iterate over this list of tokens and create a number of n-grams sequences, namely the first two words in the sentence or one sequence, then the first three are another sequence etc. The result of this will be, for the first line in the song, the following input sequences that will be generated. The same process will happen for each line, but as you can see, the input sequences are simply the sentences being broken down into phrases, the first two words, the first three words, etc. We next need to find the length of the longest sentence in the corpus. To do this, we'll iterate over all of the sequences and find the longest one with code like this. Once we have our longest sequence length, the next thing to do is pad all of the sequences so that they are the same length. We will pre-pad with zeros to make it easier to extract the label, you'll see that in a few moments. So now, our line will be represented by a set of padded input sequences that looks like this. Now, that we have our sequences, the next thing we need to do is turn them into x's and y's, our input values and their labels. When you think about it, now that the sentences are represented in this way, all we have to do is take all but the last character as the x and then use the last character as the y on our label. We do that like this, where for the first sequence, everything up to the four is our input and the two is our label. Similarly, here for the second sequence where the input is two words and the label is the third word, tokenized to 66. Here, the input is three words and the label is eight, which was the fourth word in the sentence. By this point, it should be clear why we did pre-padding, because it makes it much easier for us to get the label simply by grabbing the last token.
---------------------------------------------------------------
Теперь давайте посмотрим на код, который берёт этот корпус, и превращает его в тренировочный набор данных. Вот начало, я разберу его построчно. Во-первых, X из тренировочного набора будут называться input_sequences, и это будет Python-список. Далее для каждой строки в корпусе мы сгенерируем список токенов, используя метод токенизатора texts_to_sequences. Это преобразует строку текста вроде: "In the he town of Athy one Jeremy Lanigan" — в список токенов, представляющих слова. Затем мы пройдём в цикле по всему списку токенов и создадим подпоследовательности а именно: первые два слова в предложении станут первой подпоследовательностью, затем первые три станут второй подпоследовательностью, и т. д. В результате, для первой строки песни будут сгенерированы такие входные последовательности. То же самое сделаем с каждой строкой. Но, как видите, исходные последовательности — это просто предложения, разбитые на фразы: первые два слова, первые три слова, и т. д. Затем нам надо найти длину самого длинного предложения в корпусе. Для этого мы пройдём в цикле по всем предложениям, и найдём самое длинное с помощью такого кода. Теперь, получив наибольшую длину, следующим шагом мы дополняем все последовательности до этой длины, чтобы длина была у всех одинакова. Мы дополним их нулями спереди, чтобы было проще получить метки. Скоро вы это увидите. Итак, теперь строка представлена множеством дополненных последовательностей, которые выглядят примерно так. Получив последовательности, нам дальше следует разделить их на X и Y — входные значения и их метки. Если подумать немного, то когда предложения уже представлены таким способом, нам для разметки нужно лишь взять за X всё, кроме последнего токена, а последний токен взять за Y, т.е., метку. Вот таким образом: для первого предложения все токены от начала и по "четвёрку" — наши входные данные, а 2 — метка. И аналогично для второй последовательности: вход — два слова, а метка — третье, токеном для которого будет 66. Далее на вход пойдут три слова, и меткой будет "8", которая была четвёртым словом предложения. Теперь уже должно стать ясно, почему мы дополняли спереди: потому что это намного упрощает нам получение метки — нужно лишь взять последний токен.

5(w4)-video5: More on the training data (17.MLg_3c)

So now, we have to split our sequences into our x's and our y's. To do this, let's grab the first n tokens, and make them our x's. We'll then get the last token and make it our label. Before the label becomes a y, there's one more step, and you'll see that shortly. Python makes this really easy to do with it's less syntax. So to get my x's, I just get all of the input sequences sliced to remove the last token. To get the labels, I get all of the input sequence sliced to keep the last token. Now, I should one-hot encode my labels as this really is a classification problem. Where given a sequence of words, I can classify from the corpus, what the next word would likely be. So to one-hot encode, I can use the Keras utility to convert a list to a categorical. I simply give it the list of labels and the number of classes which is my number of words, and it will create a one-hot encoding of the labels. So for example, if we consider this list of tokens as a sentence, then the x is the list up to the last value, and the label is the last value which in this case is 70. The y is a one-hot encoded array whether length is the size of the corpus of words and the value that is set to one is the one at the index of the label which in this case is the 70th element. Okay. You now have all of the data ready to train a network for prediction. Hopefully, this was useful for you. You'll see the neural network in the next video.
---------------------------------------------------------------
Итак, теперь мы должны разделить наши последовательности на X и Y. Чтобы сделать это, давайте возьмём первые несколько токенов и сделаем их X. Затем возьмём последний токен и сделаем его меткой. Прежде чем использовать эти метки как Y, мы сделаем ещё один шаг, который вы скоро увидите. Python позволяет всё очень упростить благодаря своему синтаксису для работы со списками. Чтобы взять мои X, я просто беру срез для всех входных последовательностей, отрезая от них последний токен. А чтобы получить метки, я беру такой срез у всех входных последовательностей, чтобы остался только последний токен. И теперь мне нужно сделать унитарное кодирование моих меток, т.к. у нас задача классификации. Т.к. по заданной последовательности слов я классифицирую на основе корпуса текстов, каким окажется следующее слово. Для унитарного кодирования я могу использовать утилиту из Keras, превращающую список в категориальное значение. Я просто передаю список меток и количество классов, которое совпадает с количеством слов, — и она выполняет унитарное кодирование меток. Например, если взять в качестве предложения такой список токенов, то X — это список до последнего значения, а метка — последнее значение, в данном случае, это 70. Y — код, полученный унитарным кодированием, где длина равна размеру корпуса слов, а значение 1 имеет лишь тот элемент, номер которого совпадает со значением метки, в данном случае, это 70-й элемент. Хорошо, теперь у вас есть все необходимые данные, чтобы научить сеть предсказывать. Надеюсь, вы извлекли для себя пользу. Саму нейросеть вы увидите в последующем видео. Но сперва посмотрите, как происходит предварительная обработка данных при помощи методов, которые вы увидели в этом уроке.

6(w4)-video6: Finding what the next word should be (17.MLg_3c)

In the previous video we looked at the data, a string containing a single song, and saw how to prepare that for generating new text. We saw how to tokenize the data and then create sub-sentence n-grams that were labelled with the next word in the sentence. We then one-hot encoded the labels to get us into a position where we can build a neural network that can, given a sentence, predict the next word. Now that we have our data as xs and ys, it's relatively simple for us to create a neural network to classify what the next word should be, given a set of words. Here's the code. We'll start with an embedding layer. We'll want it to handle all of our words, so we set that in the first parameter. The second parameter is the number of dimensions to use to plot the vector for a word. Feel free to tweak this to see what its impact would be on results, but I'm going to keep it at 64 for now. Finally, the size of the input dimensions will be fed in, and this is the length of the longest sequence minus 1. We subtract one because we cropped off the last word of each sequence to get the label, so our sequences will be one less than the maximum sequence length. Next we'll add an LSTM. As we saw with LSTMs earlier in the course, their cell state means that they carry context along with them, so it's not just next door neighbor words that have an impact. I'll specify 20 units here, but again, you should feel free to experiment. Finally there's a dense layer sized as the total words, which is the same size that we used for the one-hot encoding. Thus this layer will have one neuron, per word and that neuron should light up when we predict a given word. We're doing a categorical classification, so we'll set the laws to be categorical cross entropy. And we'll use the adam optimizer, which seems to work particularly well for tasks like this one. Finally, we'll train for a lot of epoch, say about 500, as it takes a while for a model like this to converge, particularly as it has very little data. So if we train the model for 500 epochs, it will look like this.
---------------------------------------------------------------
В прошлом видео мы работали с данными, состоящими из одной строки с песней, — и посмотрели, как подготовить данные для генерации нового текста. Мы увидели, как токенизировать данные и создавать подпоследовательности слов, выбирая для них в качестве метки следующее слово в предложении. Затем мы производили унитарное кодирование меток, чтобы можно было построить нейросеть, которая предсказывала бы следующее слово для заданной фразы. Располагая данными в виде X и Y, относительно просто создать нейросеть, которая по набору слов скажет, какое слово будет следующим. Вот этот код. Мы начнём со слоя эмбеддинга. Нам нужно обработать все слова, и это указано в первом параметре. Второй параметр — необходимая размерность векторов, соответствующих словам. Не стесняйтесь покрутить этот параметр, чтобы посмотреть, как он влияет на результат, но пока я оставлю его равным 64. И, наконец, последний параметр — длина входной последовательности, она на 1 меньше, чем длина самого длинного предложения. Мы вычли единицу, потому что ранее отрезали последнее слово в каждом предложении, чтобы получить метку, так что наши последовательности будут на единицу короче максимальной длины предложений. Дальше мы добавляем LSTM. Как мы уже узнали в этом курсе, вектор состояния LSTM может донести контекст не только до соседних слов, но и на всю длину последовательности. Я выделю на вектор 20 ячеек, но, опять-таки, поэкспериментируйте, меняя этот параметр. И, наконец, полносвязный слой, размер которого равен общему числу слов, и этот же размер мы использовали для унитарного кодирования. Таким образом, в этом слое будет по одному нейрону на слово, и этот нейрон будет возбуждаться, когда мы предсказываем конкретное слово. Эта сеть выполняет категориальную классификацию, так что функция потерь должна быть categorical_crossentropy. И мы используем оптимизатор adam, который, кажется, особенно хорошо подходит для таких задач. Наконец, мы должны обучаться очень много эпох, например, 500, т.к. требуется время, чтобы подобная модель должна сойтись, в частности, при столь малом объёме данных. Если обучать модель в течение 500 эпох, мы получим подобный результат.

7(w4)-video7: Example (17.MLg_3c)

Here are a few phrases that were generated when I gave the neural network the sentence Lawrence went to Dublin, and I asked it to predict the next 10 words. We'll see the code for that in a moment, but notice that there's a lot of repetition of words. In this sentence, three of the last five words are wall, and here three of the last four are ball, and even in this one the word relations gets repeated. This is because our LSTM was only carrying context forward. Let's take a look at what happens if we change the code to be bidirectional. By adding this line simply defining the LSTM is bidirectional, and then retraining, I can see that I do converge a bit quicker as you'll see in this chart. After training and testing, I now get these sentences. They make a little bit more sense, but there's still some repetition. That being said, remember this is a song where words rhyme such as ball, all and wall, et cetera, and as such many of them are going to show up.
---------------------------------------------------------------
Вот некоторые из фраз, сгенерированных, когда я задал начало предложения "Lawrence went to Dublin" и попросил предсказать следующие 10 слов. Очень скоро мы увидим сам код, но обратите внимание, что тут очень много слов повторяется. В первом предложении 3 из 5 последних слов — "wall", а во втором 3 из 4 последних — "ball", и в последнем тоже есть повтор, слово "relations". Это произошло потому, что наша LSTM передавала контекст только вперёд. Давайте посмотрим, что произойдёт, если мы изменим слой на двунаправленный. Исправив эту строку, чтобы LSTM объявлялась как двунаправленная, а затем обучив сеть заново, я обнаружил, что сеть начала сходиться быстрее, как видно на этом графике. После обучения и тестирования я получил такие предложения. Выглядит несколько более осмысленно, но всё равно есть повторения. Стоит напомнить, что это была песня, где слова рифмуются — например, "ball", "all" и "wall" и т.д.. Поэтому их и появляется так много.

8(w4)-video8: Predicting a word (17.MLg_3c)

So now, let's take a look at how to get a prediction for a word and how to generate new text based on those predictions. So let's start with a single sentence. For example, 'Lawrence went to Dublin.' I'm calling this sentence the seed. If I want to predict the next 10 words in the sentence to follow this, then this code will tokenizer that for me using the text to sequences method on the tokenizer. As we don't have an outer vocabulary word, it will ignore 'Lawrence,' which isn't in the corpus and will get the following sequence. This code will then pad the sequence so it matches the ones in the training set. So we end up with something like this which we can pass to the model to get a prediction back. This will give us the token of the word most likely to be the next one in the sequence. So now, we can do a reverse lookup on the word index items to turn the token back into a word and to add that to our seed texts, and that's it. Here's the complete code to do that 10 times and you can tweak it for more. But do you know that the more words you predict, the more likely you are going to get gibberish? Because each word is predicted, so it's not 100 per cent certain, and then the next one is less certain, and the next one, etc. So for example, if you try the same seed and predict 100 words, you'll end up with something like this. Using a larger corpus will help, and then the next video, you'll see the impact of that, as well as some tweaks that a neural network that will help you create poetry.
---------------------------------------------------------------
Итак, посмотрим теперь, как получить предсказание для слова, и как сгенерировать новый текст, основываясь на этих предсказаниях. Давайте начнём с одного предложения. Например, "Lawrence went to Dublin". Я назову это предложение порождающим. Чтобы предсказать следующие 10 слов, следующие за этими в предложении, сначала этот код токенизирует предложение, используя метод токенизатора text_to_sequences. И поскольку у нас нет специального токена для слов не из словаря, то он проигнорирует слово Lawrence, которого нет в корпусе, и получит такую последовательность. Далее вот этот код дополнит последовательность так, чтобы её длина совпадала с длиной предложений из тренировочного набора. В итоге мы получим что-то подобное, и мы сможем передать эти данные в модель, чтобы получить предсказание. Вот этот код даст нам токен слова, которое с наибольшей вероятностью должно стоять следом. И теперь можно провести обратный поиск по словарю, чтобы обратить токен в слово и добавить его к порождающему тексту. Вот и всё! Вот полный код, который всё это делает 10 раз, и вы можете изменить его, чтобы было больше итераций. Но учтите, что чем больше слов вы предсказываете, тем вероятнее в итоге получить ахинею. Ведь каждое слово прогнозируется, и уверенность прогноза — меньше 100%. И уверенность в следующем слове ещё меньше, а в следующем за ним — ещё, и т. д.. Например, если вы попробуете с той же исходной фразой предсказать 100 слов, то получите что-то вроде этого. Помочь здесь может использование большого корпуса, и в следующем видео вы увидите, как это влияет, а заодно и несколько модификаций, с помощью которых сеть поможет вам писать стихи.

9(w4)-Check out the code! (Lab 1): (17.MLg_3c)

Here is the first notebook for this week.
---------------------------------------------------------------
C3_W4_Lab_1.ipynb
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/ungraded_labs/C3_W4_Lab_1.ipynb

10(w4)-video9: Notebook for lesson 1 (17.MLg_3c)

So here's the notebook with the basic data for a single song and traditional Irish music. Later we're going to do a corpus with lots of songs. But let's take a look at what happens with just a single song just to keep it very simple. First of all, I'm just gonna input everything that I need, and now I'm going to tokenize the data from the song. We can see the data is just this one long string with all of the lyrics. I split the lines with just the /n. So when I'm creating the corpus, i am just taking that and splitting it by a /n. Tokenizer fit on text corpus will then fit a tokenizer to all the text that's in here, and we can see the actual word index replied all etc. This number 263 is the total number of unique words that are in this corpus. So it's not a lot of words of course, as we start doing predictions based off this we're going to have a very limited dataset. So we'll see a lot of gibberish but the structure will actually work quite well. So now, I am going to create my input sequences. So my training data, that I'm going to use in the entraining the neural network itself. So what I want to do is that for each sentence, in the song or in the corpus, I'm going to take a look at each of the phrases within that and then the word that actually follows. So for example, if you look at the first sentence here in the song that's in the town of Athy one Jeremy Lanigan. When I go down here to look at the tokenizers word index for those in the town of a Athy one Jeremy Lanigan, we see that those are four, two, 66, eight etc. The important one to look at here is Lanigan which is number 70. So now if I start looking at my Xs that I've created. So my training data from my Xs that I've created. Here is one sentence that's in there. It's 4, 2, 66, 8, 67, 68, 69 which is in the town of a Athy one Jeremy. So in this case we say when our training data looks like this, we want to label it with the next word in the sequence. The next word in the sequence is 70. But we've one-hot encoded that as you can see here, with The tf.keras.utils dot to categorical. So by one-hot encoding that, when we look here we see there's a one hiding in here somewhere and it's right there. That's actually the 70th elements in the list. So our labeled for that word is a one-hot encoded to the say number 70. So when we see, when we train for sequence like this, we're saying this is what it's labeled will look like. So again, if I just print these out I get four, two, 66, eight, 67, 68 it should be followed by 70 but that's not one-hot encoded to this. So that's what my training data looks like. So now, I'm going to build a model to actually train it with that data. I'm just going to create a very simple one. It's in sequential am putting an embedding in there, am feeding the embedding the total number of words and am just going to just plot them in 64 dimensions. I'm going to create a very simple lstm, bidirectional LSTM with 20 LSTM units and then I'm going to add a dense layer between that and add at the end for the total number of words activate that by softmax. So, there are 263 total words in the corpus and we're going to train for those. So my label like he said, one-hot encoded looking like this. So that will be my last layer. I'm going to compile this it's categorical. So I'm going to use categorical cross entropy. I'm just going to use the basic atom as the optimizer. Because there's not a lot of data, I'm going to have to train it quite a lot of epochs and you'll see as I start training that my accuracy is very low to begin with, but it will improve over time.
There's not a lot of data here. It's only taking about one second as you can see for each epoch and it's increasing steadily epoch by epoch.
We can see now that we're reaching the end of it. We're in the 480 epochs that the accuracy is up into the 94,95 percent range so it's looking pretty good. We actually hit that much earlier as we'll see when we chart it, but we end up with 94.7 percent accuracy. If I charted out and plot that, we'll see we kind of hit that at around 200 epochs. We probably didn't need to go all 500 but it's nice to see it training like that. So now let's take a look at predicting words using the model that we trained on this. So if I seeded with this text Lawrence went to Dublin, I am going to ask it for the next 100 words. What it's going to do, is for each of the next 100 words it's going to create a token lists using tokenizer text sequences of the seed text. Then that token list is going to get padded to the actual length that we want. Then that's going to be passed into the model. So we're going to predict the classes for the token list that was generated off of this seed text and then we'll get an output word from that. Then that will be used to feed into the next time round to predict again to get another model. So when we start with Lawrence went to Dublin, it'll get us another word and that phrase will generate another word and that phrase will generate another word etc. So if I print that out, we'll get something like this. We can see what's actually happening here is that in the beginning it kind of looks pretty good. It's beginning to make sense. But of course because our body of texts is pretty small and each prediction is a probability, as you get further and further and further then the probabilities are decreasing and the quality of the prediction as a result goes down. So you end up with for example repeated words coming from these training words. So that's a very simple example. In the next lesson, you are going to be using a much bigger corpus of text and hopefully, the predictions will make a little bit more sense and be a little bit more poetic.
---------------------------------------------------------------
Это блокнот, где подготовлены данные на основе одной ирландской народной песни. Позже мы сделаем корпус, содержащий множество песен. Но сейчас давайте посмотрим, что будет в случае всего одной песни, чтобы пока не усложнять. Во-первых, я импортирую всё, что мне нужно. Теперь я токенизирую песню. Мы видим, что данные — это одна длинная строка, где все слова песни. Я разбил песню на строки символами \n. Так что при создании корпуса я просто разбиваю входные данные по \n. Далее метод токенизатора fit_on_texts с параметром corpus обучит токенизатор на всех имеющихся текстах, и далее мы видим получившийся словарь: "replied", "all", и так далее. 263 — это общее число уникальных слов в корпусе. Разумеется, в этом корпусе не так уж много слов, и мы начинаем предсказывать, располагая очень небольшим набором данных. Так что мы увидим много ерунды, но сама структура при этом будет довольно хороша. Итак, сейчас я создам мои входные последовательности. Т.е., тренировочные данные, которые я буду использовать при обучении нейросети. Так что мне нужно для каждого предложения в этой песне, или корпусе, посмотреть на каждую содержащуюся в них фразу, а также на слово, которое за этой фразой следует. Например, если взять первое предложение в песне, то есть: "In the town of Athy one Jeremy Lanigan" — то я иду вниз, чтобы посмотреть на индексы слов в словаре токенизатора для "In the town of Athy one Jeremy Lanigan". и видно, что это будут: 4, 2, 66, 8, и т. д. Важно заметить, что здесь у слова Lanigan номер 70. Если теперь посмотреть на те X, которые я создал, на X тренировочных данных. Вот одно предложение оттуда. Это 4, 2, 66, 8, 67, 68, 69 — "In the town of Athy one Jeremy". В данном случае, мы говорим, что когда наши тренировочные данные выглядят так, то меткой должно быть следующее слово в последовательности. А следующее слово — это 70. Но мы, как видите, применили к нему унитарное кодирование с помощью tf.keras.utils.to_categorical. И закодировав это значение, при просмотре мы видим, что где-то прячется единица, вот она. А именно, в 70-м элементе списка. Итак, наша метка для этого слова закодирована единицей в 70-й позиции. И когда мы обучаем на такой последовательности, то говорим, что на выходе метка должна быть такова. Аналогично, если я просто выведу это, то получу 4, 2, 66, 8, 67, 68 и за ними должно следовать 70, но оно закодировано вот в таком виде. Итак, вот как выглядят мои тренировочные данные. Теперь я построю модель, чтобы наконец обучить её на этих данных. Я создам очень простую модель: последовательные слои, первым идёт эмбеддинг, в который подаётся общее количество слов, и я собираюсь поместить их в 64-мерное пространство. Я создам очень простую LSTM, двунаправленную, с 20 элементами, а затем добавлю полносвязный слой после LSTM, в конец сети, с выходным размером, равным числу слов, и softmax в качестве функции активации. Итак, в корпусе всего 263 слова, и мы обучим сеть на них. Мои метки, как я уже сказал, подвергаются унитарному кодированию, и выглядят примерно так. Это будет мой последний слой. Я скомпилирую модель — она категориальная, так что я использую функцию потерь categorical_crossentropy. Оптимизатором возьму базовый Adam. И т.к. данных здесь немного, я поставлю довольно большое число эпох обучения, и вы увидите, что при запуске обучения точность начнёт с низких величин, но с течением времени будет улучшаться.
Данных здесь не очень много. Как видите, 1 эпоха обучения занимает всего порядка секунды, и точность постоянно увеличивается, эпоха за эпохой.
И вот мы приближаемся к концу, мы уже на 480-й эпохе, и точность выросла до 94-95%, что выглядит неплохо. На самом деле, как мы увидим на графике, это произошло намного раньше. Но в итоге мы получили точность 94.7%. Если теперь построить график, то мы увидим, что это значение держится в течение примерно 200 эпох. Возможно, не нужно было обучать все 500 эпох, но приятно видеть, что оно обучается так. А теперь давайте посмотрим, как модель, которую мы обучили, предсказывает слова. Если я инициирую её текстом "Lawrence went to Dublin", и спрошу про следующие 100 слов, Дальше будет вот что: для каждого из следующих 100 слов я создам список токенов, используя метод токенизатора text_to_sequences и передав в него начальный текст. Затем этот список токенов надо дополнить до нужной длины, после чего передать в модель. Мы собираемся предсказать классы по списку токенов, который был создан из этого начального текста, а затем мы преобразуем их в выходное слово. И далее его можно использовать, чтобы передать на вход модели в следующий раз, чтобы предсказать снова, и получить новое предсказание модели. Итак, мы начали с Lawrence went to Dublin, это даст нам другое слово, и суммарная фраза породит ещё одно слово, и новая фраза породит другое слово, и т.д. И если распечатать результат, то мы получим что-то вроде этого: Мы видим, что, на самом деле, поначалу всё выглядело довольно неплохо. Сначала был смысл. Но из-за того, разумеется, что наш корпус очень мал, и каждое предсказание — вероятностное, чем дальше и дальше вы заходите, тем слабее шансы, и качество предсказаний в результате ухудшается. И в итоге у вас идут, к примеру, повторяющиеся слова из обучающего набора. Это был очень простой пример. На следующем занятии вы используете корпус текстов намного большего размера, и, надеюсь, предсказания станут несколько более осмысленными и несколько более поэтичными.

11(w4)-video10: Poetry! (17.MLg_3c)

In the previous video, we used the single song to generate text. We got some text from it but once we tried to predict beyond a few words, it rapidly became gibberish. So in this video, we'll take a look at adapting that work for a larger body of words to see the impact. The good news is that it will require very little code changes, so you'll be able to get it working quite quickly. I've prepared a file with a lot of songs that has 1,692 sentences in all to see what the impact would be on the poetry that a neural network would create. To download these lyrics, you can use this code.
---------------------------------------------------------------
В предыдущем видео мы генерировали текст на основе всего лишь одной песни. Мы получили на её основе какой-то текст, но едва мы пытались предсказать чуть больше слов, как текст быстро становился абсурдным. И в этом видео мы посмотрим, как доработать наши результаты для более крупного корпуса слов, и посмотрим, что тогда будет. Хорошая новость в том, что потребуются очень небольшие изменения в коде, так что вы справитесь с ними довольно быстро. Я подготовил файл с большим количеством песен, в сумме 1692 предложений, — чтобы посмотреть, как это отразится на той поэзии, которую будет создавать нейросеть. Чтобы скачать тексты, можете использовать эту строчку кода.

12(w4)-Link to the dataset: (17.MLg_3c)

You can find the dataset of Irish song lyrics here.
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/misc/Laurences_generated_poetry.txt
---------------------------------------------------------------

13(w4)-video11: Looking into the code (17.MLg_3c)

Now instead of hard-coding the song into a string called data, I can read it from the file like this. I've updated the model a little bit to make it work better with a larger corpus of work but please feel free to experiment with these hyper-parameters. Three things that you can experiment with. First, is the dimensionality of the embedding, 100 is purely arbitrary and I'd love to hear what type of results you will get with different values.
Similarly, I increase the number of LSTM units to 150. Again, you can try different values or you can see how it behaves if you remove the bidirectional. Perhaps you want words only to have forward meaning, where big dog makes sense but dog big doesn't make so much sense. Perhaps the biggest impact is on the optimizer. Instead of just hard coding Adam as my optimizer this time and getting the defaults, I've now created my own Adam optimizer and set the learning rate on it. Try experimenting with different values here and see the impact that they have on convergence. In particular, see how different convergences can create different poetry. And of course, training for different epochs will always have an impact with more generally being better but eventually you'll hit the law of diminishing returns.
---------------------------------------------------------------
Теперь вместо прописывания строки в самом коде, в переменной data, — я прочитаю её из файла вот таким образом. Я немного изменил модель, чтобы она работала лучше с большим корпусом произведений, но не бойтесь экспериментировать с гиперпараметрами. Вот три параметра, с которыми стоит поэкспериментировать. Во-первых, размерность эмбеддинга. 100 — совершенно произвольное число, и хотел бы я узнать, какие результаты получились у вас при других значениях.
Аналогично, я увеличил число ячеек LSTM до 150. И здесь вы тоже можете пробовать разные значения, или посмотреть, как сеть поведёт себя, если убрать из неё двунаправленность. Возможно, вы захотите использовать слова только при прямой передаче контекста, когда "большая собака" имеет смысл, а "собака большая" — не особо. Пожалуй, сильнее всего я изменил оптимизатор. Вместо того, чтобы жёстко задать adam в этом коде, с конфигурацией по умолчанию, я на этот раз создал отдельный объект Adam и задал ему темп обучения. Поэкспериментируйте и тут с различными значениями, и посмотрите, как они повлияют на сходимость. В частности, как в зависимости от сходимости может меняться поэзия. И, конечно, изменение числа эпох обучения всегда будет свою играть роль. Обычно, чем оно больше, тем лучше, но можно и упереться в закон убывающей отдачи.

14(w4)-video12: Laurence the poet! (17.MLg_3c)

In a co-lab with this data and these parameters, using a GPU, it typically takes about 20 minutes to train a model. Once it's done, try a a seed sentence and get it to give you 100 words. Note that there are no line breaks in the prediction, so you'll have to add them manually to turn the word stream into poetry. Here's a simple example. I used a famous quote from a very famous movie and let's see if you can recognize it. And I tried that to see what type of poem it would give me and I got this. And it almost make sense, [LAUGH] but that's poetry for you. Help me Obi-Wan Kenobi, you're my only hope. My dear and hope as I did fly with its flavors, along with all its joys. But sure I will build, love you still, gold it did join. Do mans run away cross our country, our wedding I was down to. Off holyhead wished myself down among the pigs. Played some hearty Riggs, me embarrass. Find me brother, me chambers she gave me her story. Be Irishmen to greet you lovely Molly. Gone away from me home, home to leave the old tin cans. The foreman's chain once was shining. Sky above I think I love.
---------------------------------------------------------------
Colab с этими данными и параметрами при использовании GPU обычно обучает модель около 20 минут. Когда модель обучится, подайте в неё порождающую последовательность и получите 100 следующих слов. Обратите внимание, что предсказания не используют переводы строк, так что вам прийдётся добавить их вручную, чтобы превратить поток слов в поэзию. Вот простой пример. Я использовал известную цитату из знаменитого кинофильма. Посмотрим, узнаете ли вы её. Я решил посмотреть, что за стих модель мне выдаст, и вот что я получил. И результат почти осмысленный. Вот вам стихи. Help me Obi-Wan Kenobi, you're my only hope. My dear and hope as I did fly with its flavors, along with all its joys. But sure I will build, love you still, gold it did join. Do mans run away cross our country, are wedding I was down to. Off holyhead wished meself down among the pigs. Played some hearty rigs, me embarrass. Find me brother, me chambers she gave me who stored be Irishmen to greet you lovely Molly. Gone away from me home, home to leave the old tin cans. The foreman's chain once was shining. Sky above I think I love.

15(w4)-Check out the code! (Lab 2): (17.MLg_3c)

Let's take a look at the second notebook for this week.
C3_W4_Lab_2_irish_lyrics.ipynb
https://github.com/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/ungraded_labs/C3_W4_Lab_2_irish_lyrics.ipynb
---------------------------------------------------------------

16(w4)-video13: Your next task (17.MLg_3c)

Now, this approach works very well until you have very large bodies of text with many many words. So for example, you could try the complete works of Shakespeare and you'll likely hit memory errors, as assigning the one-hot encodings of the labels to matrices that have over 31,477 elements, which is the number of unique words in the collection, and there are over 15 million sequences generated using the algorithm that we showed here. So the labels alone would require the storage of many terabytes of RAM. So for your next task, you'll go through a workbook by yourself that uses character-based prediction. The full number of unique characters in a corpus is far less than the full number of unique words, at least in English. So the same principles that you use to predict words can be used to apply here. The workbook is at this URL, so try it out, and once you've done, that you'll be ready for this week's final exercise.
---------------------------------------------------------------
Такой подход очень хорошо работает, если только у вас не очень большой корпус текстов с огромным количеством слов. Например, если вы попробуете взять полное собрание сочинений Шекспира, вам, вероятно, не хватит памяти, потому что унитарное кодирование меток в виде матриц производится для 31 477 элементов — таково число уникальных слов в словаре. А также будет свыше 15 миллионов последовательностей, создаваемых алгоритмом, который мы с вами видели. Итак, одни только метки потребуют многих терабайтов оперативной памяти на хранение. Так что следующей вашей задачей, над которой вы поработаете самостоятельно в рабочей тетради, будет предсказание на основе отдельных символов. Число всех уникальных символов в корпусе намного меньше, чем число всех уникальных слов, — во всяком случае, в английском языке. Те же правила, которые вы использовали для предсказания слов, можно применить и здесь. Пособие находится по этой ссылке, попробуйте с ним разобраться. Справившись с этим, вы будете готовы к финальному заданию этой недели.

17(w4)-Link to generating text using a character-based RNN: (17.MLg_3c)

Find the link to generating text using a character-based RNN here.
https://www.tensorflow.org/text/tutorials/text_generation
---------------------------------------------------------------

18(w4)- Week 4 Quiz: (17.MLg_3c)

1) When predicting words to generate poetry, the more words predicted the more likely it will and up gibberish. Why?:
1. Because the probability that each word matches an existing phrase goes down the more words you create (+)
2. Because the probability of prediction compounds, and thus increases overall
3. Because you are more likely to hit words not in the training set
4. It doesn't, the likelihood of gibberish doesn't change
2) What is a major drawback of word-based training for text generation instead of character-based generation?:
1. There is no major drawback, it's always better to do word-based training
2. Because there are fare more words in a typical corpus than characters, is is much more memory intensive (+)
3. Character based generation is more accurate because there are less characters to predict
4. Word based generation is more accurate because there is a larger body of words to draw from
3) What are the critical steps in preparing the input sequences for the prediction model?:
1. Pre-padding the subprhases sequences (+)
2. Splitting the dataset into training and testing sequences
3. Generating subphrases from each line using n_gram_SEQUENCES (+)
4. Converting the seed text to a token sequence using texts_to_sequences (-)
4) In natural language processing. predicting the next item in a sequence is a classification problem. Therefore, after creating inputs and labels from the subhrases, we on-not encode the labels. What function do we use to create on-hot encoded arrays of the labels?:
1. tf.keras.preprocessing.text.one_hot
2. tf.keras.utils.img_to_array
3. tf.keras.utils.to_categorical (+)
4. tf.keras.SequenceEnqueuer
5) True of False: When building the model, we use a sigmoid activated Dense output layer with one neuron per word that lights up when we predict a give word.:
1. True
2. False (+)

19(w4)- Lecture Notes Week 4: (17.MLg_3c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

20(w4)- Programming Assignment: Predicting the next word: (17.MLg_3c)

Week 4: Predicting the next word
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C3/W4/assignment/C3W4_Assignment.ipynb

21(w4)- Wrap up: (17.MLg_3c)

Over the last four weeks you've gotten a grounding in how to do Natural Language processing with TensorFlow and Keras. You went from first principles -- basic Tokenization and Padding of text to produce data structures that could be used in a Neural Network.
You then learned about embeddings, and how words could be mapped to vectors, and words of similar semantics given vectors pointing in a similar direction, giving you a mathematical model for their meaning, which could then be fed into a deep neural network for classification.
From there you started learning about sequence models, and how they help deepen your understanding of sentiment in text by not just looking at words in isolation, but also how their meanings change when they qualify one another.
You wrapped up by taking everything you learned and using it to build a poetry generator!
This is just a beginning in using TensorFlow for natural language processing. I hope it was a good start for you, and you feel equipped to go to the next level!
---------------------------------------------------------------
За последние четыре недели вы получили представление о том, как выполнять обработку естественного языка с помощью TensorFlow и Keras. Вы перешли от первых принципов — базовой токенизации и заполнения текста к созданию структур данных, которые можно было бы использовать в нейронной сети.
Затем вы узнали о встраиваниях и о том, как слова могут быть сопоставлены с векторами, а словам с похожей семантикой заданы векторы, указывающие в одинаковом направлении, что дало вам математическую модель их значения, которую затем можно было бы передать в глубокую нейронную сеть для классификации.
Оттуда вы начали узнавать о моделях последовательностей и о том, как они помогают углубить ваше понимание настроений в тексте, не только рассматривая слова по отдельности, но и как их значения меняются, когда они определяют друг друга.
Вы закончили тем, что взяли все, что узнали, и использовали это для создания генератора стихов!
Это только начало использования TensorFlow для обработки естественного языка. Я надеюсь, что это было хорошее начало для вас, и вы чувствуете себя готовым перейти на следующий уровень!

22(w4)-video14: A conversation with Andrew Ng (17.MLg_3c)

Congrats on making it to the end of this course, where you've learned a lot about how to implement models for natural language processing. But the sequence models you've learned like the RNN, the GRU, the LSTM, they're useful for even more applications specifically time-series applications. Everything from processing weather data to processing stock market data, to try and understand "EKG" electrocardiogram that's time series electric recordings of your heart. These types of models are useful, all of these applications. So in the next course, you go deeper to learn more about how to build and train such models. So like a lot of that stuff as Andrew has mentioned just that we've done with natural language processing and sequence modeling, and even other things that we've learned in this course for example, convolutions and the convolutional neural network course, are all going to be able to come together as you start doing sequences and prediction, and we think it's going to be a really, really nice module to help really just build under those skills that you've been doing and help you move towards mastery of tensorflow. These models are important and in the next course, I hope you enjoy learning about them. So please go on to the next course.
---------------------------------------------------------------
Поздравляю с окончанием этого курса, из которого вы много узнали о том, как реализовывать модели для обработки естественного языка. Но модели, подобные РНС, УРБ, LSTM, которые вы изучили, могут работать не только с языковыми последовательностями, они имеют и другие применения — например, применимы к временным рядам. К любым: от обработки погодных данных и до биржевых показателей. Можно пытаться разбирать ЭКГ — электрокардиограмму, запись серии электрических импульсов вашего сердца. Подобные модели полезны в каждом из этих случаев. Так что в следующем курсе вы подробнее изучите, как строить и обучать такие модели. Эндрю уже о многом сказал: о том, что наши наработки в обработке естественных языков и в моделировании последовательностей, а также многое другое, чему мы научились в этом курсе — например, свёрткам и свёрточным нейросетям, — всё это, разумеется, можно объединить при работе с последовательностями и их предсказанием. И мы думаем, что это будет действительно хороший модуль, помогающий распорядиться теми умениями, которые вы приобрели, и помочь вам нарабатывать мастерство в использовании TensorFlow. Эти модели очень важны, и в следующем курсе, надеюсь, вы получите удовольствие, изучая их. Так что приглашаю вас перейти к следующему курсу.

22(w4)-Acknowledgments: (17.MLg_3c)

In addition to the original Curriculum Developers, the following people made significant contributions to the Course 3 refresh:


18.MLg_4c


(w1)Sequences and Prediction (18.MLg_4c)

(Последовательности и прогноз)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 31 minutes
Self-study: 1h 19 min
Graded tasks (Tasks to be assessed): 2

(w1) Content (18.MLg_4c)

1. 2. 3. 4.

(w1) Introduction: (18.MLg_4c)

Hi Learners and welcome to this course on sequences and prediction! In this course we'll take a look at some of the unique considerations involved when handling sequential time series data -- where values change over time, like the temperature on a particular day, or the number of visitors to your web site. We'll discuss various methodologies for predicting future values in these time series, building on what you've learned in previous courses!
---------------------------------------------------------------
Привет, учащиеся, и добро пожаловать на этот курс по последовательностям и предсказаниям! В этом курсе мы рассмотрим некоторые уникальные моменты, связанные с обработкой последовательных данных временных рядов, где значения меняются со временем, например, температура в определенный день или количество посетителей вашего веб-сайта. Мы обсудим различные методологии прогнозирования будущих значений в этих временных рядах, основываясь на том, что вы узнали на предыдущих курсах!

1(w1)-video1: Introduction, A conversation with Andrew Ng (18.MLg_4c)

Welcome to the fourth and final course of this specialization, just one course away from finishing this whole specialization and have you learnt a lot about Tensorflow. In this course, you learned about sequence models, what are sequence models? So what we're going to be focusing on is one part of sequence models, which is really time-series. Sequence models where it's a case of if you can imagine a series of data that changes over time. It might be the closing prices for stock on the stock exchange, or it could be weather. It could be how sunny it is in California on a given day, or how rainy it is in Seattle on a given day, that type of thing. So if you just imagine how an item of data changes over time and how it's measured over time. So basically almost anything like a spreadsheet, if I've a spreadsheet where I have one day per row and two columns say one for the California weather, one for the Seattle weather to document how better my life is to yours in Seattle than in California, and then we would have a new network help us model that. Exactly. So we're going to start by creating a synthetic sequence of data, so that we can start looking at what the common attributes that you see in data series are. So for example, whether data can be seasonal. It's sunnier in June than it is in January or it's wetter in November than it is in October, something along those lines. So you have that seasonality of data. You can also, in some cases, have trends of data, like whether it probably doesn't really trend although we could argue that it strangely enough idea with climate change, but like a stock data may trend upwards over time or downwards over some other times, and then of course the random factor that makes it hard to predict is noise. So you can have like seasonal data, you can have trends in your data, but then you can have noise on that data as well. So that the average temperature of a Tuesday in June and California might be 85 degrees, but it might be 85.5 degrees, it might be 84.5 degrees. So you get that noise in the data. So we want to start looking at various methods that can be used statistically in the Machine Learning to help us predict data given seasonality trend and noise. Then in this course, at the end of this course, one of the most cool applications is to use these ideas to model sunspot. Sunspot activity. Yeah. So sunspot activity is really interesting because the sun has an 11-year cycle although some astronomers tell me it's a 22-year cycle, there's actually two 11-year cycles like nestled beside each other. Will we resolve this in this course? That remains to be seen. You're going to have to study all the way through and then we'll see, but the idea then is that you do get that nice seasonality, and we have data measuring back about 250 years worth of sunspot activity. So that's on a monthly basis counting the number of sunspots that had been spotted by astronomers. So we do definitely see that 11 year cycle or maybe the 22-year cycle, and there's a lot of noise in there, the seasonality and that stuff. So it's fun to build something to protect sunspot activity. In fact, sunspot activity is very important to NASA and other space agencies because it affects satellite operations. So in this course, you'll start by learning about sequence models, a time series data, first practicing these skills and building these models on artificial Data, and then at the end of this course, you get to take all these ideas and apply them to the exciting problem of modeling sunspot activity. So let's get started. Please go on to the next video.
---------------------------------------------------------------
Добро пожаловать в четвёртый и завершающий курс данной специализации. Вам остался лишь один курс до окончания всей специализации, и вы уже многое узнали о TensorFlow. В этом курсе вы изучите модели последовательностей. Что это за модели? Итак, мы сосредоточимся на одном виде моделей последовательностей — на временных рядах. Модели последовательностей можно представить как ряд данных, меняющийся со временем. Это может быть цена закрытия для торгов на фондовой бирже, или погодные данные. Например, насколько солнечно в Калифорнии в данный день, или сколько осадков в Сиэтле на определённую дату, вот такого рода вещи. Можно просто представить, как показатель меняется со временем, и как с течением времени ведутся измерения. То есть, это почти один в один электронная таблица: можно взять таблицу, в которой на каждой строке свой день, и два столбца: в одном погода в Калифорнии, а в другом о погоде в Сиэтле, — и фиксировать в таблице, насколько лучше моя жизнь в Сиэтле, чем ваша в Калифорнии, — а затем мы возьмём новую нейросеть, чтобы всё это смоделировать. Именно. Так что начнём с создания искусственной последовательности данных, чтобы можно было посмотреть, какие общие признаки можно выделить в рядах данных. Например, данные о погоде носят сезонный характер. В июне солнечнее, чем в январе, а погода в ноябре лучше, чем в октябре. Что-то в таком роде. Итак, в данных бывает сезонность. Также иногда можно видеть в данных тренды (тенденции) — пожалуй, в погоде трендов особо нет, хотя можно возразить, что тренд есть, если взять идею изменения климата. Но как в биржевых данных, какой-то период может наблюдаться восходящий тренд, а в другой — нисходящий. Наконец, есть, разумеется, и фактор случайности, затрудняющий предсказания шум. Итак, в данных бывает сезонность, могут присутствовать временные тренды, а также может присутствовать шум. И средняя температура в июньский четверг для Калифорнии может быть 30 градусов Цельсия, [85 по Фаренгейту - прим. пер.] но также может и 30,5 градусов, а может быть и 29,5. Так что, в данных есть шум. И мы обратимся к различным методам, которые можно применить для машинного обучения в области статистики, чтобы прогнозировать данные с учётом сезонности, трендов и шума. В этом курсе, в конце этого курса, одним из самых захватывающих приложений станет использование этих знаний для моделирования солнечных пятен. Солнечной активности, да. Солнечная активность — это очень интересно, ведь у Солнца есть 11-летний цикл, хотя некоторые астрономы говорят, что это 22-летний цикл, в котором два 11-летних цикла, идущих друг за другом. Мы разберёмся с этим вопросом в данном курсе? Это надо посмотреть. Сначала нужно изучить весь материал, а там увидим. Но идея в том, чтобы взять эту отчётливую сезонность, а у нас есть данные измерений солнечной активности на протяжении 250 лет. Это данные от ежемесячных подсчётов отмечаемых астрономами солнечных пятен. Так что мы определённо увидим этот 11-летний цикл — а может, 22-летний цикл, и в нём очень много шума, сезонность, и тому подобное. Увлекательное дело — построить инструмент для прогноза солнечной активности. Солнечная активность очень важна для NASA и других космических агентств, т.к. она влияет на работу спутников. Итак, в этом курсе, в котором вы начинаете изучать моделирование последовательностей, модели временных рядов, и сперва потренируетесь в этом, создавая модели на искусственных данных. А в конце этого курса вы возьмёте все эти идеи и примените их в захватывающей задаче моделирования солнечной активности. Итак, приступим. Приглашаем вас в следующее видео.

2(w1)-video2: Time series examples (18.MLg_4c)

Welcome to this course on sequences and prediction, a part of the TensorFlow in practice specialization. In this course, we'll focus on time series, where you'll learn about different types of time series before we go deeper into using time series data. This week, you'll focus on time series themselves. We'll go through some examples of different types of time series, as well as looking at basic forecasting around them. You'll also start preparing time series data for machine learning algorithms. For example, how do you split time series data into training, validation, and testing sets? We'll explore some best practices and tools around that to get you ready for week 2, where you'll start looking at forecasting using a dense model, and how it differs from more naive predictions based on simple numerical analysis of the data. In week 3, we'll get into using recurrent neural networks to forecast time series. We'll see the stateless and stateful approaches, training on windows of data, and you'll also get hands-on in forecasting for yourself. Finally, in week 4, you'll add convolutions to the mix and put everything you've worked on together to start forecasting some real world data, and that's measurements of sunspot activity over the last 250 years. So let's get started with a look at time series, what they are, and the different types of them that you may encounter. Time series are everywhere. You may have seen them in stock prices, weather forecasts, historical trends, such as Moore's law. Here, I've plotted the number of transistors per square millimeter, where I grouped chip releases by year, and then drew the Moore's law trend line from the first data item, where you can see a correlation. If you want some really fun correlations, here's one from Tyler Vigen's site of Spurious Correlations. This one is a time series correlation of total revenue generated by video game arcades versus computer science doctorates awarded in the United States. While all of these are quite familiar, they begged the question, what exactly is a time series? It's typically defined as an ordered sequence of values that are usually equally spaced over time. So for example, every year in my Moore's law charts or every day in the weather forecast. In each of these examples, there is a single value at each time step, and as a results, the term univariate is used to describe them. You may also encounter time series that have multiple values at each time step. As you might expect, they're called Multivariate Time Series. Multivariate Time Series charts can be useful ways of understanding the impact of related data. For example, consider this chart of births versus deaths in Japan from 1950 to 2008. It clearly shows the two converging, but then deaths begin to outstrip births leading to a population decline. Now, while they could be treated as two separate univariate time series, the real value of the data becomes apparent when we show them together as a multivariate. Also consider this chart showing the global temperature against CO2 concentration. As univariates, they would show a trend, but when combined, the correlation is very easy to see adding further value to the data. Movement of a body can also be plotted as a series of univariates or as a combined multivariate. Consider, for example, the path of a car as it travels. A time step zero is at a particular latitude and longitude. As subsequent time steps, these values changed based on the path of the car. The acceleration of the car, in other words, it's not moving at a constant speed, means that the spaces between the time steps also change in size, in this case getting larger. But what if we were to plot the direction of the car as univariates. Based on its heading, we could see that the longitude of the car decreases over time, but its latitude increases, and as such you will get charts like these.
---------------------------------------------------------------
Добро пожаловать в этот курс, посвящённый последовательностям и прогнозированию, часть специализации "TensorFlow на практике". В этом курсе мы сосредоточимся на временных рядах. Вы узнаете о разных типах временных рядов, прежде чем углубиться в работу с такими данными. На этой неделе мы сфокусируемся на самих временных рядах. Мы пройдёмся по нескольким примерам временных рядов разных типов и посмотрим на базовое прогнозирование их значений. Вы также познакомитесь с подготовкой временных рядов для алгоритмов машинного обучения. Узнаете, например, как разделять данные временных рядов на тренировочный, валидационный и тестовый наборы. Мы изучим передовой опыт и инструменты в этой части, чтобы вы были готовы ко второй неделе, когда мы займёмся прогнозированием с использованием полносвязных моделей, и посмотрим, чем это отличается от более наивных прогнозов, основанных на простом численном анализе данных. На третьей неделе мы погрузимся в использование рекуррентных нейросетей для предсказания временных рядов. Мы посмотрим на подходы с сохранением состояния и без сохранения состояния, а также обучение на окне данных. И вы попрактикуетесь в предсказаниях самостоятельно. Наконец, на четвёртой неделе вы добавите к своему ассортименту свёртки, и сведёте воедино то, над чем вы работали, чтобы предсказывать уже реальные данные. Это будут измерения солнечной активности за последние 250 лет. Итак, давайте начнём с рассмотрения временных рядов: что они из себя представляют, и с какими различными их типами вы можете столкнуться. Временные ряды есть во всём вокруг. Вы могли видеть их на примере биржевых цен, прогнозов погоды, исторических трендов, таких как закон Мура. Тут я построил график числа транзисторов на квадратный миллиметр, сгруппировав чипы по годам их выпуска, а затем нарисовал линию тренда закона Мура из самой первой точки, и здесь можно видеть корреляцию. А если хотите и правда забавных корреляций, то вот одна, с сайта иллюзорных корреляций Тайлера Вигена. Это корреляция между совокупными прибылями от аркадных видеоигр — и числом присвоенных докторских степеней по информатике в США. Хотя это всё довольно знакомо, встаёт вопрос: что же такое временные ряды? Обычно их определяют как упорядоченную последовательность значений, которые обычно равномерно распределены во времени. Например, с шагом в год, как в моём графике, посвящённом закону Мура, или раз в день, в случае прогноза погоды. В каждом из этих примеров каждому шагу по времени соответствует единственное значение, а потому для их описания используется термин "одновариантный". Также вы можете столкнуться с временными рядами, имеющими по несколько значений на каждый временной интервал. Как вы можете догадаться, они называются многовариантными временными рядами. Графики многовариантных временных рядов могут быть полезны для понимания взаимосвязей в данных. Например, посмотрите на этот график рождений и смертей в Японии с 1950 до 2008 гг.. Здесь отчётливо видно, что две линии сходятся, а затем смерти начинают превалировать над рождениями, что ведёт к уменьшению населения. И, хотя можно рассматривать их как два отдельных одновариантных временных ряда, но истинное их значение проступает, когда мы показываем их вместе, как многовариантный ряд. Также посмотрите на этот график с глобальной температурой и концентрацией CO2. Если считать их одновариантными, они покажут тренд, но если их скомбинировать, то очень легко увидеть корреляцию, придающую значимости этим данным. Движение тела тоже можно изобразить как одновариантные или скомбинированные многовариантные временные ряды. Взять, например, путь едущей машины. В нулевой момент времени она находится в точке с некоторой широтой и долготой. В последующие моменты эти значения изменяются в соответствии с путём машины. Ускорение машины, или, иными словами, то, что она движется не с постоянной скоростью, — означает, что длина пройденного пути между отсечками — также меняется, в данном случае, растёт. Но что, если мы изобразим движение машины как одновариантные ряды? По направлению езды мы видим, что долгота машины уменьшается со временем, но широта растёт, и в итоге получаются вот такие графики.

3(w1)-video3: Machine learning applied to time series (18.MLg_4c)

Now these are just a few examples of the types of things that can be analyzed using time series. And just about anything that has a time factor in it can be analyzed in this way. So what types of things can we do with machine learning over time series? The first and most obvious is prediction of forecasting based on the data. So for example with the birth and death rate chart for Japan that we showed earlier. It would be very useful to predict future values so that government agencies can plan for retirement, immigration and other societal impacts of these trends. In some cases, you might also want to project back into the past to see how we got to where we are now. This process is called imputation. Now maybe you want to get an idea for what the data would have been like had you been able to collect it before the data you already have. Or you might simply want to fill in holes in your data for what data doesn't already exist. For example, in our Moore's law chart from earlier. There was no data for some years because there were no chips released in those years, and you can see the gaps here. But with imputation, we can fill them up. Additionally, time series prediction can be used to detect anomalies. For example, in website logs so that you could see potential denial of service attacks showing up as a spike on the time series like this. The other option is to analyze the time series to spot patterns in them that determine what generated the series itself. A classic example of this is to analyze sound waves to spot words in them which can be used as a neural network for speech recognition. Here for example, you can see how a sound wave is split into words. Using machine learning, it becomes possible to train a neural network based on the time series to recognize words or sub words.
---------------------------------------------------------------
Мы увидели лишь несколько примеров явлений, которые можно проанализировать с помощью временных рядов. Так можно анализировать практически всё, что связано со временем. Как же можно применить машинное обучение к временным рядам? Первое, и наиболее очевидное, — прогнозирование по имеющимся данным. Возьмём, например, график рождений и смертей для Японии, который мы уже видели. Для государственных учреждений было бы очень полезно предсказать значения в будущем, чтобы планировать по ним пенсионную и иммиграционную политику, а также иные социальные программы. В некоторых случаях может понадобиться направить предсказания на прошлое, чтобы увидеть, как мы попали в нынешнюю ситуацию. Это называется "импутация" (подстановка). Возможно, хочется понять, как могли выглядеть показатели, если бы вы начали собирать их ещё раньше. Или возможно, вы просто хотите заполнить пробелы в ваших данных, те точки, где данных нет. Например, в графике для закона Мура, который мы уже видели, для каких-то годов нет данных, потому что в эти годы не выходило новых чипов, и в таких местах видны разрывы. Но мы можем их заполнить импутацией. Кроме того, предсказание временных рядов можно использовать при поиске аномалий. Например, в логах веб-сайта, чтобы увидеть потенциальную атаку "отказ в обслуживании", проявляющуюся в виде пика в данных, похожего на этот. Ещё одна возможность — анализировать временные ряды в поиске шаблонов, позволяющих выяснить, что сгенерировало сам этот ряд. Классический тому пример — анализ звуковых волн, чтобы выделить в них слова, и на основе этого можно создать нейросеть для распознавания речи. Например, здесь показано, как волна делится на слова. Используя машинное обучение, можно обучить нейросеть, основанную на временных рядах, распознаванию слов или слогов.

4(w1)-video4: Common patterns in time series (18.MLg_4c)

Time-series come in all shapes and sizes, but there are a number of very common patterns. So it's useful to recognize them when you see them. For the next few minutes we'll take a look at some examples. The first is trend, where time series have a specific direction that they're moving in. As you can see from the Moore's Law example we showed earlier, this is an upwards facing trend. Another concept is seasonality, which is seen when patterns repeat at predictable intervals. For example, take a look at this chart showing active users at a website for software developers. It follows a very distinct pattern of regular dips. Can you guess what they are? Well, what if I told you if it was up for five units and then down for two? Then you could tell that it very clearly dips on the weekends when less people are working and thus it shows seasonality. Other seasonal series could be shopping sites that peak on weekends or sport sites that peak at various times throughout the year, like the draft or opening day, the All-Star day playoffs and maybe the championship game. Of course, some time series can have a combination of both trend and seasonality as this chart shows. There's an overall upwards trend but there are local peaks and troughs. But of course, there are also some that are probably not predictable at all and just a complete set of random values producing what's typically called white noise. There's not a whole lot you can do with this type of data. But then consider this time series. There's no trend and there's no seasonality. The spikes appear at random timestamps. You can't predict when that will happen next or how strong they will be. But clearly, the entire series isn't random. Between the spikes there's a very deterministic type of decay. We can see here that the value of each time step is 99 percent of the value of the previous time step plus an occasional spike. This is an auto correlated time series. Namely it correlates with a delayed copy of itself often called a lag. This example you can see at lag one there's a strong autocorrelation. Often a time series like this is described as having memory as steps are dependent on previous ones. The spikes which are unpredictable are often called Innovations. In other words, they cannot be predicted based on past values. Another example is here where there are multiple autocorrelations, in this case, at time steps one and 50. The lag one autocorrelation gives these very quick short-term exponential delays, and the 50 gives the small balance after each spike. Time series you'll encounter in real life probably have a bit of each of these features: trend, seasonality, autocorrelation, and noise. As we've learned a machine-learning model is designed to spot patterns, and when we spot patterns we can make predictions. For the most part this can also work with time series except for the noise which is unpredictable. But we should recognize that this assumes that patterns that existed in the past will of course continue on into the future. Of course, real life time series are not always that simple. Their behavior can change drastically over time. For example, this time series had a positive trend and a clear seasonality up to time step 200. But then something happened to change its behavior completely. If this were stock, price then maybe it was a big financial crisis or a big scandal or perhaps a disruptive technological breakthrough causing a massive change. After that the time series started to trend downward without any clear seasonality. We'll typically call this a non-stationary time series. To predict on this we could just train for limited period of time. For example, here where I take just the last 100 steps. You'll probably get a better performance than if you had trained on the entire time series. But that's breaking the mold for typical machine, learning where we always assume that more data is better. But for time series forecasting it really depends on the time series. If it's stationary, meaning its behavior does not change over time, then great. The more data you have the better. But if it's not stationary then the optimal time window that you should use for training will vary. Ideally, we would like to be able to take the whole series into account and generate a prediction for what might happen next. As you can see, this isn't always as simple as you might think given a drastic change like the one we see here. So that's some of what you're going to be looking at in this course. But let's start by going through a workbook that generates sequences like those you saw in this video. After that we'll then try to predict some of these synthesized sequences as a practice before later we'll move on to real-world data.
---------------------------------------------------------------
Временные ряды бывают всевозможных форм и размеров, но есть несколько очень распространённых шаблонов. Стоит научиться различать их при взгляде на данные. В ближайшие несколько минут мы рассмотрим некоторые примеры. Первый — это тренд, когда есть определённое направление, в котором ряд движется. Как видите на примере закона Мура, который мы показывали раньше, это — восходящий тренд. Другой случай — сезонность, которая проявляется в том, что шаблон повторяется с предсказуемой периодичностью. Например, посмотрите на этот график, отражающий число активных пользователей на сайте для программистов. В нём прослеживается отчётливый шаблон регулярных провалов. Можете угадать, что это? А если я вам скажу, что значения высоки в течение 5 единиц времени, и низкие в течение 2? Тогда вы скажете, что, очевидно, провалы приходятся на выходные, когда работает меньше людей, и это пример сезонности. Другие сезонные ряды могут наблюдаться в местах для шопинга, где резко растёт посещаемость по выходным дням, или спортивные сооружения, где наблюдаются пики в конкретные моменты в году, как драфт, день открытия сезона, игра всех звёзд, плей-офф, и, возможно, матч за чемпионство. И, конечно, в некоторых временных рядах могут сочетаться тренд и сезонность, как показано на этом графике. Тут есть общий восходящий тренд, но есть также и локальные пики и провалы. И, конечно, возможны временные ряды, которые, вероятно, не прогнозируемы вовсе, являясь лишь набором случайных величин, производящих т.н. белый шум. Мало что можно поделать с такими данными. А теперь посмотрите на этот временной ряд. Тут нет тренда, и нет сезонности. Выбросы появляются в случайные моменты времени. Вы не можете предсказать, когда произойдёт следующий и насколько сильным он будет. Но ряд, очевидно, в целом не случаен. Между выбросами он демонстрирует очень предсказуемый тип убывания. Мы видим, что значение на каждом шаге составляет 99% от значения предыдущего шага плюс случайный выброс. Это автокорреляционный временной ряд. Название подсказывает, что он коррелирует со сдвинутой по времени копией себя, которую часто называют "лаг". На этом примере видно, что сильная автокорреляция происходит при лаге 1. Часто такие временные ряды описываются как имеющие память, поскольку новый отсчёт зависит от предыдущих. Непредсказуемые выбросы часто называют инновациями. Другими словами, их нельзя предсказать, основываясь на прошлых значениях. Другой наш пример — со множественными автокорреляциями, в данном случае, с лагами 1 и 50. Автокорреляция с лагом 1 даёт очень быстрое краткосрочное экспоненциальное убывание, а с лагом 50 даёт небольшой остаток после каждого выброса. Временные ряды, которые вам встретятся в реальных задачах, возможно, будут иметь понемногу от каждого из этих шаблонов: тренд, сезонность, автокорреляция и шум. Как мы узнали, модели в машинном обучении предназначены находить шаблоны, а когда мы их обнаруживаем, то можем делать предсказания. По большей части, это же применимо и ко временным рядам — кроме шума, который непредсказуем. Но стоит сознавать: предполагается, что шаблоны, существовавшие в прошлом, сохранятся и в будущем. Конечно, реальные временные ряды не всегда такие простые. Их поведение может резко измениться в один миг. Например, этот временной ряд имел положительный тренд и отчётливую сезонность вплоть до шага 200. Но затем нечто произошло, и это полностью изменило поведение ряда. Если это биржевая цена, то, возможно, это был крупный финансовый кризис, или большой скандал, или, возможно, взрывной прорыв в технологиях, породивший масштабные перемены. И после этого временной ряд начал проявлять нисходящий тренд без явной сезонности. Мы будем называть такие временные ряды нестационарными. Чтобы предсказать его значение, мы должны обучаться лишь на ограниченном временном промежутке. Например, здесь я взял только последние 100 шагов. И в таком случае, вероятно, качество прогнозов будет выше, чем при обучении на всём временном ряде. Это ломает шаблон типичного машинного обучения, где мы всегда предполагаем, что чем больше данных, тем лучше. Для предсказания временных рядов тут всё зависит от самого временного ряда. Если он стационарный, то есть, его поведение не меняется со временем, — тогда отлично, чем больше у вас данных, тем лучше. Но если он нестационарный, тогда оптимальный интервал, который нужно использовать в обучении, — будет меняться. В идеале, нам бы хотелось принимать во внимание весь временной ряд и выдавать предсказание, что случится дальше. Но, как видите, это не всегда так просто, как можно подумать, с учётом резких изменений вроде тех, что здесь показаны. Итак, это была часть того, что вы увидите в данном курсе. Но давайте начнём с того, что посмотрим блокнот, где генерируются последовательности, подобные тем, что мы здесь видели. А затем уже постараемся предсказать некоторые из этих синтезированных последовательностей чтобы попрактиковаться, прежде чем перейти к реальным данным.

5(w1)-video5: Introduction to time series (18.MLg_4c)

Let's take a look at time series and the various attributes of time series using Python. This notebook is available as part of the course and I'll provide a link to it. I recommend that you watch this video first and then try the notebook for yourself afterwards. I'll start by running the nodes containing the imports as well as a couple of helper functions. One to plot the series and one to return a trend. So now, let's plot our first very simple time series. Even though it's a straight line, it's also an example of the time series. The x-axis in this case is time and the y value is the value of the function at that time. Next, we'll take a look at adding a seasonal pattern to our time series. These functions contain a seasonal pattern and then seasonality that just uses the same pattern. We'll now plot that. As we investigate the graph, we can see clear peaks and troughs. But in addition to that, there are smaller, regular spikes. This could be seen as a rough simulation of a seasonal value. For example, maybe profits for shop that are negative on the day the store is closed, peaking a little the day after, decaying during the week and then peaking again on the weekend. What if we now add a trend to this so that the seasonal data while still following the pattern increases over time? Maybe simulating a growing business so when we plot it, we'll see the same pattern but with an overall upward trend. What if we now add another feature that's common in time series, noise? Here's a function that add some noise to a series and when we call that and plot the results and their impact on our time series, we now get a very noisy series, but one which follows the same seasonality as we saw earlier. It's interesting because at this point, the human eye may miss a lot of the seasonality data but a computer will hopefully be able to spot it. Next we can explore a little bit of Autocorrelation, but first here are a couple of functions that can add it for you. Here is where we add the autocorrelation to the series and plot it. There are two different autocorrelation functions and I'll plot both so that you can see the effects of each. This one is particularly interesting because you can see the repeated pattern despite different scales. There is a pattern and then a sharp fall off followed by the same pattern on a smaller scale with the same fall off, which is then shrunk et cetera. If I change autocorrelation functions and run it again, we can then see the other function. Now, I'm going to add some impulses and plot them. Nothing too exciting here yet. But when I start adding some autocorrelations to this, then we'll see some of the behavior that we had discussed earlier where from our pulse we have a decay away from it but the decay could be interrupted by another pulse. This decay could be autocorrelated so that after the pulse it decays but then the decay autocorrelates. So we have these decreasing curves. Then we'll try another autocorrelation and another. Now, let's add them to simulate a seasonal time series that has an impact full of events that changes everything. For example, that might be a financial series that shows seasonality, but then something changes like a failure of the business or big news events. Hopefully this exploration of some synthetic data to show some of the attributes of time-series was helpful for you to understand some of the terminology. I have found that synthetic data like this is very useful if you want to learn how to use Machine Learning to understand and predict on data. In the next lesson, you'll take the first steps towards predicting the next values in a synthetic series before later in the course, you'll start applying what you've learned to real-world data.
---------------------------------------------------------------
Давайте поглядим на временные ряды и их различные свойства с помощью Python. Этот блокнот доступен в составе курса, и я дам ссылку на него. Рекомендую сначала посмотреть это видео, а затем уже поработать с блокнотом самостоятельно. Я начну с запуска строк, содержащих импорт библиотек и пару вспомогательных функций. Одна строит график ряда, а другая возвращает тренд. Итак, построим график первого, очень простого ряда. Пусть это и прямая линия — но это тоже пример временного ряда. По оси абсцисс отложено время, а по оси ординат — значение функции в это время. Дальше мы посмотрим, как добавить к нашему временному ряду сезонную закономерность. В этой функции заключён сезонный паттерн, и функция seasonality (сезонность) всегда использует этот паттерн. Построим её график. Изучая график, мы видим отчётливые пики и провалы. Но вдобавок к ним есть также регулярные выбросы меньшего масштаба. Это можно считать грубой имитацией сезонных изменений значений. Это может быть, например, прибыль магазина, отрицательная в тот день, когда магазин закрыт, и подскакивающая на следующий день, а затем убывающая в течение недели, и снова выходящая на пик в выходные. Что, если мы сейчас добавим сюда тренд, чтобы сезонность по-прежнему отвечала своему паттерну, но величина со временем росла? Возможно, это симуляция растущего бизнеса. Так что, построив график, мы увидим тот же шаблон, но с восходящим трендом. Что, если теперь добавить другой часто встречающийся во временных рядах элемент — шум? Вот функция, которая добавляет немного шума в ряд, и если её вызвать и вывести на график результат, то, как он влияет на наш временной ряд, — то мы получим очень зашумлённый ряд, но он, тем не менее, подчиняется той же сезонности, которую мы видели раньше. Это любопытно, ведь теперь человеческий глаз может упустить большую часть сезонной составляющей, но мы надеемся, что компьютер сумеет её заметить. Дальше можно немного поисследовать автокорреляции, но сперва добавим пару функций для её добавления в ряд. И здесь мы добавляем к ряду автокорреляцию и строим график. Тут две различных автокорреляционных функции, и я выведу обе, чтобы вы могли увидеть, как сказывается каждая из них. Эта — особенно интересная, потому что здесь виден повторяющийся шаблон, вопреки разнице в масштабе. Вот шаблон, затем резкое падение, за которым следует тот же шаблон в меньшем масштабе с таким же падением, которое уменьшается, и т. д. Если я изменю автокорреляционную функцию и запущу её опять, то мы увидим другие результаты. А теперь давайте добавим немного шума. И попробуем другую функцию автокорреляции. И ещё одну. А сейчас давайте добавим их к симуляции сезонных временных рядов, где есть важные события, меняющие всё. Например, это может быть финансовый ряд, демонстрирующий сезонность, но потом что-то меняется — например, провал в бизнесе, или важные новости. Я добавлю несколько импульсов и выведу на график. Пока ничего впечатляющего. Но когда я начинаю добавлять автокорреляцию, то мы увидим что-то, похоже на поведение, которое мы обсуждали раньше, где после всплеска значения убывают, но один всплеск может быть прерван другим. И это убывание может быть автокоррелированным, так что после всплеска идёт спад, но затем спад автокоррелирует, и у нас получаются эти нисходящие кривые. Надеюсь, такое изучение искусственных данных с целью продемонстрировать некоторые свойства временных рядов — помогло вам понять часть терминологии. Я обнаружил, что синтетические данные, подобные этим, — очень полезны, когда нужно научиться использовать машинное обучение для понимания и предсказания данных. В следующем уроке вы сделаете первые шаги к тому, чтобы предсказывать последующие значения в искусственных рядах — прежде чем переходить в рамках курса к применению ваших новых знаний к реальным данным.

6(w1)-Where to find the notebooks for this course: (18.MLg_4c)

All notebooks in this course can be run in either Google Colab or Coursera Labs. You don’t need a local environment set up to follow the coding exercises. You will be taken to Google Colab for the ungraded labs while for the assignments, you will be taken automatically to Coursera Labs.
However, if you want to run them on your local machine, the ungraded labs and assignments for each week can be found in this Github repository
under the C4 folder. If you already have git installed on your computer, you can clone it with this command:
git clone https://github.com/https-deeplearning-ai/tensorflow-1-public
If not, please follow the guides here to install git on your operating system. Once you’ve cloned the repo, you can do a git pull once in a while to make sure that you get the latest updates to the notebooks.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
You will need these packages if you will run the notebooks locally:
tensorflow==2.7.0
numpy==1.20.1
matplotlib==3.2.2
---------------------------------------------------------------
Все блокноты в этом курсе можно запускать либо в Google Colab, либо в Coursera Labs. Вам не нужна локальная среда, настроенная для выполнения упражнений по программированию. Вы будете перенаправлены в Google Colab для невыставленных лабораторных работ, а для заданий вы будете автоматически перенаправлены в лаборатории Coursera.
Однако, если вы хотите запустить их на своем локальном компьютере, неоцененные лабораторные работы и задания на каждую неделю можно найти в этом репозитории Github.
в папке C4. Если на вашем компьютере уже установлен git, вы можете клонировать его с помощью этой команды:
клон git https://github.com/https-deeplearning-ai/tensorflow-1-public
Если нет, следуйте инструкциям здесь, чтобы установить git в вашей операционной системе. После того, как вы клонировали репозиторий, вы можете время от времени выполнять git pull, чтобы убедиться, что вы получаете последние обновления для блокнотов.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
Вам понадобятся эти пакеты, если вы будете запускать блокноты локально:

7(w1)-Introduction to time series notebook (Lab 1): (18.MLg_4c)

Here is the link to the notebook that Laurence just showed in the previous screencast.
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W1/ungraded_labs/C4_W1_Lab_1_time_series.ipynb
Ungraded Lab: Introduction to Time Series Plots
---------------------------------------------------------------

8(w1)-[IMPORTANT] Have questions, issues or ideas? Join our Community!: (18.MLg_4c)

Hello!
We’ve created a community for you to:
Ask for help on assignments and other course content.
Discuss course topics.
Share your knowledge with other learners.
Build your network
Find out about exciting DeepLearning.AI news, events and competitions!
To go to the community for this course, tick the checkbox below indicating you agree to use the app responsibly, then click on the "Launch App” button.
If you are new to the community, click on the "Launch App" button to create your account and access our community.
We created this User Guide for you. https://sites.google.com/deeplearning.ai/deeplearningaifaq/home
Be sure to check out the Code of Conduct community guidelines. https://sites.google.com/deeplearning.ai/deeplearningaifaq/policies/code-of-conduct
aving trouble accessing our community after clicking the “Launch App” button? Fill out this form to explain your issue and we will get back to you.
https://docs.google.com/forms/d/e/1FAIpQLSeaLh4yDVyewvthP2ThVaz0daU9fACkihRlSfT-CMUw12Gidw/viewform
---------------------------------------------------------------

9(w1)-video6: Train, validation and test sets (18.MLg_4c)

In the previous videos this week, you saw all of the different factors that make up the behavior of a time series. Now we'll start looking at techniques, given what we know, that can be used to then forecast that time series. Let's start with this time series containing, trend seasonality, and noise and that's realistic enough for now. We could, for example, take the last value and assume that the next value will be the same one, and this is called naive forecasting. I've zoomed into a part of the data set here to show that in action. We can do that to get a baseline at the very least, and believe it or not, that baseline can be pretty good. But how do you measure performance? To measure the performance of our forecasting model,. We typically want to split the time series into a training period, a validation period and a test period. This is called fixed partitioning. If the time series has some seasonality, you generally want to ensure that each period contains a whole number of seasons. For example, one year, or two years, or three years, if the time series has a yearly seasonality. You generally don't want one year and a half, or else some months will be represented more than others. While this might appear a little different from the training validation test, that you might be familiar with from non-time series data sets. Where you just picked random values out of the corpus to make all three, you should see that the impact is effectively the same. Next you'll train your model on the training period, and you'll evaluate it on the validation period. Here's where you can experiment to find the right architecture for training. And work on it and your hyper parameters, until you get the desired performance, measured using the validation set. Often, once you've done that, you can retrain using both the training and validation data. And then test on the test period to see if your model will perform just as well. And if it does, then you could take the unusual step of retraining again, using also the test data. But why would you do that? Well, it's because the test data is the closest data you have to the current point in time. And as such it's often the strongest signal in determining future values. If your model is not trained using that data, too, then it may not be optimal. Due to this, it's actually quite common to forgo a test set all together. And just train, using a training period and a validation period, and the test set is in the future. We'll follow some of that methodology in this course. Fixed partitioning like this is very simple and very intuitive, but there's also another way. We start with a short training period, and we gradually increase it, say by one day at a time, or by one week at a time. At each iteration, we train the model on a training period. And we use it to forecast the following day, or the following week, in the validation period. And this is called roll-forward partitioning. You could see it as doing fixed partitioning a number of times, and then continually refining the model as such. For the purposes of learning time series prediction in this course, will learn the overall code for doing series prediction. Which you could then apply yourself to a roll-forward scenario, but our focus is going to be on fixed partitioning.
---------------------------------------------------------------
В предыдущих видео этой недели вы увидели всевозможные факторы, определяющие поведение временного ряда. Теперь мы рассмотрим методы, которые позволяют, с учётом наших знаний, предсказывать эти временные ряды. Начнём вот с такого временного ряда, содержащего тренд, сезонность и шум, на данном этапе он достаточно реалистичен. Можно, например, взять последнее значение и предположить, что следующее будет точно таким же — это называется наивным прогнозом. Я здесь увеличил часть графика, чтобы показать работу данного метода. Можно взять этот метод за отправную точку, и, хотите верьте, хотите — нет, но и этот прогноз может быть довольно хорош. Но как измерить его качество? Чтобы измерить качество модели предсказаний, нам, как правило, нужно разделить временной ряд на диапазоны: обучающий, валидационный и тестовый. Это называется фиксированным разделением. Если во временном ряде наблюдается сезонность, то обычно стоит убедиться, что в каждый из наборов попадёт целое число сезонов. Например, 1, 2 или 3 года, если у временного ряда годичная сезонность. Обычно не стоит брать 1.5 года — ведь тогда некоторые месяцы в выборке будут представлены более остальных. И хотя это может на первый взгляд отличаться от разбиения на обучающий, валидационный и тестовый наборы, который вам может быть знаком по работе с другими наборами данных, где данные просто берутся случайным образом из корпуса, образуя все три набора, — но вы увидите, что эффект будет, по сути, тот же самый. Дальше вы обучаете свою модель на данных из обучающего интервала и оцениваете её качество на валидационном интервале. Здесь можно экспериментировать в поиске подходящей для обучения архитектуры, и дорабатывать её, а также подстраивать гиперпараметры, пока вы не достигнете нужного качества, измеряемого по валидационной выборке. Обычно, добившись этого, вы обучаете модель заново на обоих наборах разом: обучающем и валидационном. А затем проверяете на тестовых данных, проверяя, что и на них работать будет не хуже. И если это так, то можно пойти на необычный шаг: снова обучить модель, используя вдобавок и тестовые данные. Почему можно так поступать? Потому, что тестовые данные — это данные, наиболее близкие к настоящему моменту [из имеющихся]. И потому они часто сильнее всего способны влиять на значения в будущем. Если модель обучена без использования, в т.ч., и этих данных — то она может оказаться неоптимальной. Из-за этого довольно часто от тестового набора данных отказываются вовсе, обучая с использованием лишь обучающего и валидационного интервалов, а тестовый набор "находится" в будущем. В этом курсе мы иногда будем придерживаться данной методологии. Подобное фиксированное разделение — очень простое и интуитивное, но есть и другой способ. Можно начать с короткого обучающего периода, постепенно увеличивая его, скажем, на один день за раз, или на неделю за раз. На каждой итерации мы обучаем модель на обучающем периоде и используем её, чтобы предсказать следующий день или неделю валидационного периода. Это разделение выборки с переносом. Можно расценивать его как серию фиксированных разбиений с постепенным уточнением модели. Поскольку цель курса — научиться предсказывать временные ряды, мы изучим общий код для предсказательных моделей, который вы сможете доработать для разделения с переносом, здесь же мы сосредоточимся на фиксированном разделении.

10(w1)-video7: Metrics for evaluating performance (18.MLg_4c)

Once we have a model and a period, then we can evaluate the model on it, and we'll need a metric to calculate their performance. So let's start simply by calculating the errors, which is the difference between the forecasted values from our model and the actual values over the evaluation period. The most common metric to evaluate the forecasting performance of a model is the mean squared error or mse where we square the errors and then calculate their mean. Well, why would we square it? Well, the reason for this is to get rid of negative values. So, for example, if our error was two above the value, then it will be two, but if it were two below the value, then it will be minus two. These errors could then effectively cancel each other out, which will be wrong because we have two errors and not none. But if we square the error of value before analyzing, then both of these errors would square to four, not canceling each other out and effectively being equal. And if we want the mean of our errors' calculation to be of the same scale as the original errors, then we just get its square root, giving us a root means squared error or rmse. Another common metric and one of my favorites is the mean absolute error or mae, and it's also called the mean absolute deviation or MAE. And in this case, instead of squaring to get rid of negatives, it just uses their absolute value. This does not penalize large errors as much as the mse does. Depending on your task, you may prefer the mae or the mse. For example, if large errors are potentially dangerous and they cost you much more than smaller errors, then you may prefer the mse. But if your gain or your loss is just proportional to the size of the error, then the mae may be better. Also, you can measure the mean absolute percentage error or mape, this is the mean ratio between the absolute error and the absolute value, this gives an idea of the size of the errors compared to the values. If we look at our data, we can measure the MAE using code like this. The keras metrics libraries include an MAE that can be called like this. With the synthetic data we showed earlier, we're getting about 5.93, let's consider that our baseline.
---------------------------------------------------------------
Располагая моделью и временным интервалом, можно оценить модель на этом интервале, для чего нам нужна какая-то мера качества. Сначала станем просто вычислять ошибки — разницу между значениями, предсказываемыми моделью, и реальными значениями за оцениваемый период. Чаще всего в качестве метрики качества предсказательных моделей берут среднеквадратичную ошибку (MSE), где отдельные ошибки возводятся в квадрат, а затем вычисляется их среднее. Но зачем возводить в квадрат? Для того, чтобы избавиться от отрицательных значений. Например, если мы ошиблись на 2, завысив значение, то ошибка будет 2. Но если предсказали на 2 меньше, ошибка будет -2. И такие ошибки будут взаимно сокращаться что неправильно: у нас две ошибки, а не их отсутствие. Но если мы возведём величину ошибки в квадрат, то обе этих ошибки будут равны 4, не сокращаясь друг с другом, а будучи равными. И если нужно, чтобы среднее от всех ошибок было того же масштаба, что и исходные значения ошибок, то нужно просто извлечь квадратный корень, что даёт нам корень из среднеквадратической ошибки, или RMSE. Ещё одна популярная метрика, одна из моих любимых — средняя абсолютная ошибка (MAE) также её называют средним абсолютным отклонением (MAD) Здесь, чтобы избавиться от отрицательных значений, вместо возведения в квадрат берутся абсолютные значения ошибок. Это не так сильно штрафует за большие ошибки, как MSE. В зависимости от задачи, вы можете предпочесть MAE или MSE. Например, если большие ошибки потенциально опасны и обходятся дороже, чем маленькие, тогда можно выбрать MSE. Но если ваша выгода или потеря пропорциональна размеру ошибки, то MAE может подойти лучше. Кроме того, можно измерять среднюю абсолютную ошибку в процентах, или MAPE. Это среднее отношение модуля ошибки к модулю значения. Оно даёт представление о размере ошибки в сравнении с прогнозируемыми величинами. Для наших данных можно измерить MAE, используя такой код. Библиотеки метрик Keras включают метрику MAE, которую можно вызвать так. На ранее показанных синтетических данных мы получаем около 5,93, Возьмём это значение за отправную точку.

11(w1)-video8: Moving average and differencing (18.MLg_4c)

A common and very simple forecasting method is to calculate a moving average. The idea here is that the yellow line is a plot of the average of the blue values over a fixed period called an averaging window, for example, 30 days. Now this nicely eliminates a lot of the noise and it gives us a curve roughly emulating the original series, but it does not anticipate trend or seasonality. Depending on the current time i.e. the period after which you want to forecast for the future, it can actually end up being worse than a naive forecast. In this case, for example, I got a mean absolute error of about 7.14. One method to avoid this is to remove the trend and seasonality from the time series with a technique called differencing. So instead of studying the time series itself, we study the difference between the value at time T and the value at an earlier period. Depending on the time of your data, that period might be a year, a day, a month or whatever. Let's look at a year earlier. So for this data, at time T minus 365, we'll get this difference time series which has no trend and no seasonality. We can then use a moving average to forecast this time series which gives us these forecasts. But these are just forecasts for the difference time series, not the original time series. To get the final forecasts for the original time series, we just need to add back the value at time T minus 365, and we'll get these forecasts. They look much better, don't they? If we measure the mean absolute error on the validation period, we get about 5.8. So it's slightly better than naive forecasting but not tremendously better. You may have noticed that our moving average removed a lot of noise but our final forecasts are still pretty noisy. Where does that noise come from? Well, that's coming from the past values that we added back into our forecasts. So we can improve these forecasts by also removing the past noise using a moving average on that. If we do that, we get much smoother forecasts. In fact, this gives us a mean squared error over the validation period of just about 4.5. Now that's much better than all of the previous methods. In fact, since the series is generated, we can compute that a perfect model will give a mean absolute error of about four due to the noise. Apparently, with this approach, we're not too far from the optimal. Keep this in mind before you rush into deep learning. Simple approaches sometimes can work just fine.
---------------------------------------------------------------
Популярный и очень простой метод прогнозирования состоит в вычислении скользящего среднего. Идея заключается в том, что что жёлтая линия отражает среднее значение значений голубой линии на фиксированном интервале — так называемом окне усреднения. Например, за 30 дней. Тем самым устраняется большая часть шума, выдавая кривую, грубо моделирующую исходный ряд, но здесь не учитываются ни тренды, ни сезонность. В зависимости от выбора момента времени, т.е. от периода, следом за которым должно идти предсказание будущего, результат может оказываться даже хуже, чем при наивном прогнозе. В этом случае, например, я получил среднюю абсолютную ошибку около 7.14. Один из способов этого избежать — убрать тренд и сезонность из временного ряда при помощи дифференцирования. Вместо изучения самого ряда, мы изучим разницу между значениями в момент T и в более ранний момент времени. В зависимости от временной шкалы, периодом [дифференцирования] может быть год, день, месяц или другое значение. Давайте возьмём интервал в год. Для этих данных с моментом времени T-365 мы получим разностный временной ряд, у которого нет тренда и нет сезонности. Тогда можно будет использовать скользящее среднее в предсказаниях для этого временного ряда, что даст нам вот такой прогноз. Но это прогноз лишь для разностного временного ряда, а не для исходного. Чтобы получить окончательный прогноз для исходного временного ряда, нужно прибавить обратно значение в момент T-365, и тогда мы получим такой прогноз. Выглядит намного лучше, не так ли? Если мы померим среднюю абсолютную ошибку на валидационном интервале, то получим около 5.8. Это немного лучше, чем наивный прогноз, но не сильно. Вы могли заметить, что наше скользящее среднее устранило много шума, но итоговый прогноз по-прежнему довольно шумный. Откуда этот шум взялся? Он пришёл из прошлых значений, которые мы добавили обратно к прогнозу. Так что можно этот прогноз улучшить, убрав также шум из прошлого, усреднив его скользящим окном. Если так сделать, получится намного более гладкий прогноз. И он даёт нам среднюю квадратичную ошибку на валидационном интервале всего порядка 4.5. И это гораздо лучше, чем у всех предыдущих методов. И поскольку ряд сгенерирован, можно подсчитать, что идеальная модель даст среднюю абсолютную ошибку около 4 — из-за шума. Очевидно, наш текущий подход не так уж далёк от оптимального. Имейте это в виду, прежде чем бросаться в глубокое обучение. Простые подходы иногда тоже отлично работают.

12(w1)-video9: Trailing versus centered windows (18.MLg_4c)

Note that we used the trailing window when computing the moving average of present values But we used a centered window to compute the moving average of past values. Moving averages using centered windows can be more accurate than using trailing windows. But we can't use centered windows to smooth present values since we don't know future values. However, to smooth past values we can afford to use centered windows. Okay, so now we've looked at a few statistical methods for predicting the next values in a time series. In the next video, you'll take a look at a screencast of this prediction in action. Once you've done the statistical forecasting, the next step of course will be to apply the machine-learning techniques you've been learning all along in TensorFlow and you'll do that next week.
---------------------------------------------------------------
Обратите внимание, что при вычислении скользящего среднего для текущего значения мы берём запаздывающее окно, от t-32 до t-1, Но при усреднении скользящим окном значений в прошлом мы используем центрированное окно от момента (t - 1) год, минус 5 дней — и до (t - 1) года плюс 5 дней. Скользящее среднее с центрированным окном может быть точнее, чем запаздывающее окно. Но мы не можем брать центрированное окно для сглаживания текущих значений, т.к. нам неизвестны будущие значения. Но чтобы сгладить прошлые значения, мы можем позволить себе использовать центрированное окно. Итак, мы сейчас рассмотрели некоторые статистические методы прогнозирования последующих значений во временном ряду. В следующем видео вы посмотрите рабочую демонстрацию такого прогнозирования. После статистического прогнозирования следующим этапом курса станет применение методов машинного обучения из TensorFlow, которые вы изучали. Этим вы и займётесь на следующей неделе.

13(w1)-video10: Forecasting (18.MLg_4c)

Let's take a look at running some statistical forecasting on the Synthetic Dataset that you've been working with. This should give us some form of baseline that we'll see if we can beat it with Machine Learning. You saw the details in the previous video and you'll go through this workbook in this video. The next code block condenses a lot of what you saw in the previous lessons. It will create a time series with trend, seasonality, and noise. You can see it in the graph here. Now to create a training validation set split, we'll simply split the array containing the data at index 1,000, and we will chart it. Again, we can see that the seasonality is maintained and it's still trending upwards. It also contains some noise. The validation set is similar and while the charts may appear different, checkout the x-axis. You can see that we've zoomed in quite a bit on it, but it is the same pattern. Now let's start doing some of the naive prediction. The first super simple prediction is to just predict the value at time period plus one. It's the same as the value of the current time period. So we'll create data called Naive Forecasting that simply copies the training data at time t minus 1. When we plot it, we see the original series in blue and the predicted one in orange. It's hard to make it out. So let's zoom in a little. We're looking at the start of the data, and that's sharp climb this C. So when we zoom in, we can see that the orange data is just one time-step after the blue data. This code will then print the mean squared and mean absolute errors. We'll see what they are. We get. 61.8 and 5.9 respectively. We'll call that our baseline. So now let's get a little smarter and try a moving average. In this case, the point in time t will be average of the 30 points prior to it. This gives us a nice smoothing effect. If we print out the error values for this, we'll get values higher than those for the naive prediction. Remember, for errors lower as better. So we can say that this is actually worse than the naive prediction that we made earlier on. So let's try a little trick to improve this. Since the seasonality on this Data is one year or 365 days, let's take a look at the difference between the data at time t and the data from 365 days before that. When we plot that, we can see that the seasonality is gone and we're looking at the raw data plus the noise. So now, if we calculate a moving average on this data, we'll see a relatively smooth moving average not impacted by seasonality. Then if we add back the past values to this moving average, we'll start to see a pretty good prediction. The orange line is quite close to the blue one. If we calculate the errors on this, you'll see that we have a better value than the baseline. We're definitely heading in the right direction. But all we did was just add in the raw historic values which are very noisy. What if, instead, we added in the moving average of the historic values, so we're effectively using two different moving averages? Now, our prediction curve is a lot less noisy and the predictions are looking pretty good. If we measure their overall error, the numbers agree with our visual inspection, the error rate has improved further. That was a pretty simple introduction to using some mathematical methods to analyze a series and get a basic prediction. With a bit of fiddling, we got a pretty decent one too. Next week, you'll look at using what you've learned from Machine Learning to see if you can improve on it.
---------------------------------------------------------------
Давайте посмотрим, как статистическое прогнозирование работает на наших синтетических данных. Мы возьмём его за отправную точку, и посмотрим, получится ли у нас превзойти её с помощью машинного обучения. Отдельные детали вы видели в прошлом видео, а в данном видео мы пройдёмся по всему блокноту. Перед началом убедитесь, что работаете в окружении Python 3 и с использованием GPU. Часть кода потребует наличия TensorFlow 2.0. Поэтому убедитесь, что он у вас есть. Этот код выведет его текущую версию. Если ваша версия меньше, чем 2.0, то нужно будет установить свежую версию. Чтобы установить её, используйте этот код. На момент записи этого курса, TensorfFlow 2.0 был на стадии первой бета-версии. Чтобы установить обновлённую, можно свериться с актуальной инструкцией на TensorFlow.org. Разобравшись с этим, вы увидите приглашение перезапустить окружение. Убедитесь, что вы это сделали. Проверьте, что у вас по-прежнему окружение с Python 3 и GPU, и запустите скрипт снова. Вы должны увидеть, что версия 2.0 теперь установлена. Следующий блок кода сводит воедино многое из того, что вы видели в предыдущем уроке. Здесь создаётся временной ряд с трендом, сезонностью и шумом. Вы можете увидеть его на этом графике. Чтобы теперь разделить данные на тренировочные и валидационные, просто разделим массив с данными по 1000-му элементу, и отобразим это на графике. И здесь тоже видно, что сезонность сохраняется, и тренд по-прежнему восходящий. А также присутствует шум. Валидационный набор похож, и хотя графики могут выглядеть по-разному, обратите внимание на ось абсцисс. Вы увидите, что масштаб [в валидации] несколько мельче, но паттерн тот же самый. Теперь давайте начнём с наивного прогноза. Первый очень простой прогноз — предсказывать значение на следующий временной период как равное значению в текущий период. Создадим массив под названием naive_forecasting, куда просто копируются тренировочные данные за момент времени t - 1. Когда мы построим график, то увидим исходный ряд голубого цвета и предсказанный оранжевого. Трудно их различить, так что давайте немного увеличим. Мы смотрим на начало ряда, и видим там резкий подъём. Увеличив график, мы видим, что оранжевая линия просто на шаг впереди голубой линии. Следующий код выводит среднеквадратичную и среднюю абсолютную ошибки. Посмотрим, каковы они. Мы получили 61,8 и 5,9 соответственно. Возьмём их за точку отсчёта. А теперь давайте будем немного умнее, и попробуем скользящее среднее. В этом случае значение в момент T будет средним из 30 предшествующих значений. Это даёт хороший эффект сглаживания. Если мы выведем значения ошибок для этого метода, то получим значения выше, чем при наивном прогнозе. Помните, что чем ниже ошибка, тем лучше. Поэтому можно сказать, что это на самом деле хуже наивного прогноза, выполненного ранее. Но давайте попробуем небольшой улучшающий трюк. Так как сезонность в этих данных — это один год, или 365 дней, то давайте посмотрим на разницу между данными в момент времени T и данными за 365 дней до этого. Когда мы выведем её на график, то увидим, что сезонность ушла, и мы видим плоские данные плюс шум. И если вычислять скользящее среднее на этих данных, то мы увидим относительно гладкое скользящее среднее, не подверженное сезонности. И если затем мы прибавить обратно прошлые значения к этому скользящему среднему, то мы увидим вполне неплохой прогноз. Оранжевая линия довольно близка к синей. Если мы посчитаем ошибки данного предсказания, то вы увидите, что их значения лучше, чем у базового варианта. Мы определенно движемся в верном направлении. Но мы здесь просто добавили сырые исторические данные — а в них полно шума. Что, если взамен добавить скользящее среднее по историческим данным, задействовав сразу два разных скользящих средних? Теперь наша прогнозируемая кривая куда менее шумная, и прогноз выглядит довольно хорошо. Если измерить общую ошибку, то цифры согласуются с нашей визуальной проверкой: уровень ошибки снова был улучшен. Это было довольно простое знакомство с тем, как использовать некоторые математические методы в анализе рядов и получать простейшие прогнозы. Немного повозившись, мы получили вполне приличный прогноз. На следующей неделе вы увидите, как использовать ваши знания машинного обучения, чтобы узнать, можно ли ещё улучшить этот результат.

14(w1)-Forecasting notebook (Lab 2): (18.MLg_4c)

Here is the link to the notebook that demonstrates statistical methods in forecasting.
C4_W1_Lab_2_forecasting.ipynb
Ungraded Lab: Statistical Forecasting on Synthetic Data
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W1/ungraded_labs/C4_W1_Lab_2_forecasting.ipynb#scrollTo=HrvQysecM9my
---------------------------------------------------------------

15(w1)- Week 1 Quiz: (18.MLg_4c)

1) What is an example of a Univariate time series?:
1 Baseball scores
2. Fashion items
3. Hour by hour temperature (+)
4. Hour by hour weather
2) What is an example of a Multivariate time series?:
1. Hour by hour weather (+)
2. Fashion items
3. Baseball scores
4. Hour by hour temperature
3) What is imputed data?:
1. Data that has been withheld for various reasons
2. A projection of unknown (usually past or missing) data (+)
3. A good prediction of future data
4. A bad prediction of future data
4) A sound wave is a good example of time series data:
1. False
2. True (+)
5) What is a Seasonality?:
1. Data that is only available at certain times of the year
2. Data aligning to the 4 seasons of the calendar
3. Weather data
4. A regular change in shape of the data (+)
6) What is trend?:
1. An overall consistent downward direction for data
2. An overall consistent flat direction for data
3. An overall direction for data regardless of direction (+)
4. An overall consistent upward direction for data
7) In the context of time series, what is noise?:
1. Sound waves forming a time series
2. Data that doesn't have a trend
3. Unpredictable changes in time series data (+)
4. Data that doesn't have seasonality
8) What is autocorrelation?:
1. Data that automatically lines up in trends
2. Data that automatically lines up seasonally
3. Data that doesn't have noise
4. Data that follows a predictable shape, even if the scale is different (+)
9)What is a non-stationary time series?:
1. One that has a disruptive event breaking trend and seasonality (+)
2. One that moves seasonally
3. One that has a constructive event forming trend and seasonality
4. One that is consistent across all seasons

16(w1)-Week 1 Wrap up: (18.MLg_4c)

This week you explored the nature of time-series data, and you saw some of its more common attributes such as seasonality and trend. You also looked at some statistical methods for predicting time series data.
Next week, you're going to start to look into using DNNs for time series classification, including the important task of understanding how to break up a time series into training and validation data.
---------------------------------------------------------------
На этой неделе вы изучили природу данных временных рядов и познакомились с некоторыми их наиболее распространенными атрибутами, такими как сезонность и тенденция. Вы также рассмотрели некоторые статистические методы прогнозирования данных временных рядов.
На следующей неделе вы начнете изучать использование DNN для классификации временных рядов, включая важную задачу понимания того, как разбить временной ряд на обучающие и проверочные данные.

17(w1)-Lecture Notes Week 1: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
https://community.deeplearning.ai/login
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/ungradedLti/smWBG/important-have-questions-issues-or-ideas-join-our-community
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI
as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------

18(w1)-Assignment Troubleshooting Tips: (18.MLg_4c)

ere are some general guidelines before submitting your assignments in this course. Please keep this in mind not only for this week's assignment but for the next ones as well:
1. Make sure to save your work before clicking the Submit button. If not, you might get an error message like in the code cell below. Remember that everything that you need to fill in within the graded functions is initialized to None.
2. Please do not rename the notebook. The grader will look for the original filename and its associated metadata so you should work on the file that is automatically opened when you click the Launch Notebook button. If you try to submit a renamed notebook, then you might also get an error like the one shown above.
3. Please do not modify any code outside the START CODE HERE and END CODE HERE tags. Your solution should only be placed between these markers to ensure successful grading. Modifying function parameters and other test cells will likely break the grader. If you want to experiment with these, you can do so after you have successfully passed the assignment.
4. After following the tips above and the grader still gives you 0/100, it's possible that the metadata needed for grading is corrupted. Please get a new lab notebook by refreshing your workspace (instructions here). Then copy your solutions into the new notebook. Make sure that all cells still run as expected then resubmit.
5. If you have further questions, please create a topic in the Discourse community instead of the Coursera discussion forums. You can join by
following the instructions here. You will get help there quicker because several mentors and your fellow learners are monitoring the posts. Just make sure to create the topic in the correct course category.
---------------------------------------------------------------

19(w1)-(Optional) Downloading your Notebook and Refreshing your Workspace: (18.MLg_4c)

This course uses Coursera Labs to provide a notebook environment and to grade your work. There might be some instances where you need to download your notebooks or refresh your workspace to start from scratch. This reading item outlines the steps to do so.
Downloading your Notebook
In case you need to download your notebook for troubleshooting or running in your local environment, you can follow these simple steps:
From the Menu Bar of the notebook you are working on, Click File → Save and Checkpoint to first save your progress.
Click File → Download as → Notebook (.ipynb). This should start downloading the file into your local machine.
---------------------------------------------------------------

19(w1)-Programming Assignment: Working with generated time seriese: (18.MLg_4c)

Week 1: Working with time series:
Welcome! In this assignment you will be working with time series data. All of the data is going to be generated and you will implement several functions to split the data, create forecasts and evaluate the quality of those forecasts.
Let's get started!

NEXT week_2 (18.MLg_4c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w2)Deep Neural Networks for Time Series (18.MLg_4c)

(Глубокие нейронные сети для временных рядов)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 25 minutes
Self-study: 1h 36 min
Graded tasks (Tasks to be assessed): 2

(w2) Content (18.MLg_4c)

1. 2. 3. 4.

(w2) Introduction: (18.MLg_4c)

Having explored time series and some of the common attributes of time series such as trend and seasonality, and then having used statistical methods for projection, let's now begin to teach neural networks to recognize and predict on time series!
---------------------------------------------------------------
Изучив временные ряды и некоторые общие атрибуты временных рядов, такие как тенденция и сезонность, а затем применив статистические методы для прогнозирования, давайте теперь начнем учить нейронные сети распознавать и прогнозировать временные ряды!

1(w2)-video1: Introduction, A conversation with Andrew Ng (18.MLg_4c)

Welcome to the second week of this course. You learned about how to compute statistical analysis of a time series. In this week, you'll learn to apply a new network to these sequences. Yeah, we'll start with a relatively simple DNN, and if you remember DNNs all the way back like at the beginning of the specialization, so you're going to be able to bring those skills to bear on time-series data. So we're going to build a very simple DNN just like a three-layer DNN. Then one technique though that's I find really useful that you're going to learn this week, is being able to tune the learning rate of the optimizer. We'll all spent a lot of time hand-tuning learning rate. One of my most distinctive memories from couple of decades ago was a summer intern at Microsoft research staying up until 3:00 AM in the office, hand-tuning learning rates. I wish I could tune my own learning rate sometimes. So I think giving people a systematic way to do this, will be very useful. Yeah. I think so, and I know I've spent too many sleepless nights at it. So we tried to automate it here and so teach you a technique for automating it and hopefully it'll be useful, and hopefully it'll help you to start learning how to predict your time series data. By the end of this week, you have trained DNN on time series data that you saw last week and you get to see how well it does. Please go onto to the next video.
---------------------------------------------------------------
Добро пожаловать на вторую неделю этого курса. Вы узнали, как проводить статистический анализ временных рядов. На этой неделе вы научитесь применять к этим рядам нейросети. Да, мы начнём с довольно простой полносвязной нейросети (DNN), и если вы помните, DNN мы проходили давно, в самом начале специализации. И вы сможете перенести эти навыки на исследование временных рядов. Итак, мы собираемся построить очень простую DNN, всего лишь трёхслойную DNN. Затем применим один метод, который я нахожу очень полезным, и вы узнаете его на этой неделе: это возможность настраивать скорость обучения оптимизатора. Мы все потратили много времени, вручную подстраивая скорость обучения. Одно из моих наиболее ярких воспоминаний двадцатилетней давности — это когда я проходил летнюю стажировку в центре исследований Microsoft, просиживая в офисе до 3 утра и настраивая вручную скорость обучения. Хотелось бы мне подкрутить свою собственную скорость обучения. И я думаю, что если мы дадим людям системный подход к настройке, то это будет очень полезно. Да. Тоже так думаю, и знаю, что провёл за этим делом слишком много бессонных ночей. Итак, мы постарались автоматизировать настройку и научить вас методике её автоматизации, и я надеюсь, это будет полезно, и поможет вам начать изучение того, как предсказывать значения ваших временных рядов. К концу этой недели вы обучите DNN, используя временной ряд с прошлой недели, и посмотрите, насколько хорошо она с этим справится. Пожалуйста, переходите к следующему видео.

2(w2)-Preparing features and labels notebook (Lab 1): (18.MLg_4c)

In the next couple of videos, Laurence will demonstrate a series of commands to prepare features and labels. You can use the notebook here
to follow along and see links to the documentation of each command.
C4_W2_Lab_1_features_and_labels.ipynb
Ungraded Lab: Preparing Time Series Features and Labels
---------------------------------------------------------------

3(w2)-video2: Preparing features and labels (18.MLg_4c)

Last week you looked at creating a synthetic seasonal data set that contained trend, seasonality, and a bit of noise. You also looked at some statistical methods for analyzing the data set and making predictions from it. Some of the results you got were actually quite good, but there was no machine learning applied yet. This week, you're going to look at using some machine learning methods with the same data. Let's see where machine learning can take us. First of all, as with any other ML problem, we have to divide our data into features and labels. In this case our feature is effectively a number of values in the series, with our label being the next value. We'll call that number of values that will treat as our feature, the window size, where we're taking a window of the data and training an ML model to predict the next value. So for example, if we take our time series data, say, 30 days at a time, we'll use 30 values as the feature and the next value is the label. Then over time, we'll train a neural network to match the 30 features to the single label. So let's, for example, use the tf.data.Dataset class to create some data for us, we'll make a range of 10 values. When we print them we'll see a series of data from 0 to 9. So now let's make it a little bit more interesting. We'll use the dataset.window to expand our data set using windowing. Its parameters are the size of the window and how much we want to shift by each time. So if we set a window size of 5 with a shift of 1 when we print it we'll see something like this, 01234, which just stops there because it's five values, then we see 12345 etc, etc,. Once we get towards the end of the data set we'll have less values because they just don't exist. So we'll get 6789, and then 789, etc, etc,. So let's edit our window a little bit, so that we have regularly sized data. We can do that with an additional parameter on the window called drop_remainder. And if we set this to true, it will truncate the data by dropping all of the remainders. Namely, this means it will only give us windows of five items. So when we print it, it will now look like this, starting at 01234 and ending at 56789. Great, now let's put these into numpy lists so that we can start using them with machine learning. Good news is, is that this is super easy, we just call the .numpy method on each item in the data set, and when we print we now see that we have a numpy list. Okay, next up is to split the data into features and labels. For each item in the list it kind of makes sense to have all of the values but the last one to be the feature, and then the last one can be the label. And this can be achieved with mapping, like this, where we split into everything but the last one with :-1, and then just the last one itself with -1. Which gives us this output when we print, which now looks like a nice set of features and labels. Typically, you would shuffle their data before training. And this is possible using the shuffle method. We call it with the buffer size of ten, And when we print the results, we'll see our features and label sets have been shuffled. Finally, we can look at batching the data, and this is done with the batch method. It'll take a size parameter, and in this case it's 2. So what we'll do is we'll batch the data into sets of two, and if we print them out, we'll see this. We now have three batches of two data items each. And if you look at the first set, you'll see the corresponding x and y. So when x is four, five, six and seven, our y is eight, or when x is zero, one, two, three, you'll see our y is four. Okay, now that you've seen the tools that let us create a series of x and y's, or features and labels, you have everything you need to work on a data set in order to get predictions from it. We'll take a look at a screen cast of this code next, before moving on to creating our first neural networks to run predictions on this data.
---------------------------------------------------------------
На прошлой неделе вы посмотрели, как создать синтетический набор данных с сезонностью, в котором есть тренд, сезонность и немного шума. Вы также рассмотрели некоторые статистические методы анализа таких данных и их прогнозирования. Некоторые из полученных результатов были уже весьма неплохи, но дело ещё не дошло до применения машинного обучения. На этой неделе вы рассмотрите, как на тех же данных использовать некоторые методы машинного обучения. Давайте посмотрим, к чему машинное обучение может нас привести. Прежде всего, как и в любой другой задаче машинного обучения, нам нужно разбить данные на признаки и метки. В данном случае признаками будет некоторое число значений ряда, а меткой — следующее за ними значение. Назовём количество значений, которые будем считать признаками, — размером окна, т.к. мы берём окно с данными, и обучаем модель предсказывать следующее значение. Например, если брать из нашего ряда, данные, например, за 30 дней сразу, то 30 значений мы возьмём в качестве признаков, а следующее за ними — в качестве метки. А затем мы научим нейронную сеть находить соответствие между 30 признаками и единственной меткой. Давайте, возьмём, например, класс tf.data.Dataset, чтобы создать некоторые данные. Возьмём диапазон из 10 значений. Когда мы напечатаем их, мы увидим ряд чисел от 0 до 9. А теперь сделаем немного поинтереснее. Мы используем dataset.window, чтобы расширить наш набор данных с помощью окон. Его параметры — это размер окна и шаг, на который мы хотим каждый раз сдвигать окно. Если взять размер окна как 5, и шаг в 1, и вывести результат на экран, то мы увидим что-то подобное: 0, 1, 2, 3, 4 — на этом вывод прекратится, т.к. в окно попадает лишь 5 значений. Далее мы увидим 1, 2, 3, 4, 5, и т. д., и т. п. Ближе к концу набора данных значений становится меньше, т.к. дальше их просто не существует. Так что мы получим 6, 7, 8, 9, потом 7, 8, 9, и т.д. Немного подправим наше окно, чтобы данные были одного размера. Это можно сделать при помощи дополнительного параметра метода window под названием drop_remainder. Если задать его равным True, метод обрежет данные, отбросив все остатки. А именно, это означает, что он вернёт нам только окна из пяти элементов. И когда мы распечатаем новый вариант, он будет выглядеть так, начинаясь с 0, 1, 2, 3, 4 и заканчиваясь на 5, 6, 7, 8, 9. Отлично, а теперь давайте поместим их в списки numpy, чтобы можно было использовать их для машинного обучения. Хорошая новость в том, что это очень просто: мы лишь вызываем метод .numpy для каждого элемента в наборе данных, и когда мы их выводим, то видим, что это списки numpy. Так, теперь нужно разделить данные на признаки и метки. Для каждого элемента в списке имеет смысл сделать все значения, кроме последнего, — признаками, а последний — меткой. А это можно получить отображением, как здесь, где мы разделили все списки на две части: всё, кроме последнего, при помощи [:-1], и сам последний — [-1:] При выводе мы получаем такой результат, теперь это похоже на хороший набор признаков и меток. Как правило, данные перед обучением перемешивают. Это можно сделать, используя метод shuffle. Мы вызываем его с размером буфера, равным 10, т.к. именно столько элементов содержится в наших данных. И когда мы выводим результат, то видим, что наши наборы признаков и меток были перемешаны. Наконец, посмотрим, как объединить данные в пакеты — это делается методом batch. Он принимает размер пакета как параметр — в данном случае, 2. Тем самым, мы делим данные на пакеты по два элемента, и если их вывести на экран, то увидим вот что. Теперь у нас есть три пакета, по два элемента данных в каждом. Если посмотреть на первый набор, то вы увидите там соответствующие х и у. Так, когда x = [4, 5, 6, 7], то y = [8], а когда x = [0, 1, 2, 3], то вы увидите, что y = [4]. Теперь, когда вы увидели инструменты, позволяющие создавать наборы х и у, т.е., признаков и меток, — у вас есть всё необходимое для подготовки данных к получению предсказаний. Этот же самый код мы рассмотрим поэтапно, прежде чем перейти к созданию нашей первой нейросети и получению прогнозов на этих данных.

4(w2)-video3: Preparing features and labels (screencast) (18.MLg_4c)

In the previous video, you saw how to prepare a time series for machine learning by windowing the data. You saw the code to create a very simple dataset, and then you learned how you can prepare that dataset as features and labels or x's and y's. In this video, you'll go through a screencast of a notebook that contains all of that code. First, we'll create a simple dataset, and it's just a simple range containing 10 elements from zero to nine. We'll print each one out on its own line as you can see. Next, we'll window the data into chunks of five items, shifting by one each time. We'll see that this gives us the output of the first five items, and then the second five items, and then the third five items, etc. At the end of the dataset, when there isn't enough data to give us five items, you'll see shorter lines. To just get chunks of five records, we'll set drop_reminder to true. When we run it, we'll see that our data looks like this. We've got even sets that are the same size. TensorFlow likes its data to be in numpy format. So we can convert it easily by calling the dot numpy method and when we print it, we can see it's now listed in square brackets. Next up is to split into x's and y's or features and labels. We'll take the last column as the label, and we'll split using a lambda. We'll split the data into `:-1`, which is all of the columns except the last one, and `-1` which is the last one only. Now we can see that we have a set of four items and a single item. Remember that the `-1` denotes the last value in the list, and `:-1` denotes everything about the last value. As such, we can see zero, one, two, three and one, two, three, four before the split just for example. Next of course, is to shuffle the data. This is achieved with the shuffle method. This helps us to rearrange the data so as not to accidentally introduce a sequence bias. Multiple runs will show the data in different arrangements because it gets shuffled randomly. Finally, comes batching. By setting a batch size of two, our data gets batched into two x's and two y's at a time. For example, as we saw earlier, if x is zero, one, two, three, we can see that the corresponding y is four or if x is five, six, seven, eight, then our y is nine. So that's the workbook with the code that splits a data series into windows. Try it out for yourself, and once you're familiar with what it does, proceed to the next video. There you'll move to the seasonal dataset that you've been using two dates, and with this windowing technique, you'll see how to set up x's and y's that can be fed into a neural network to see how it performs with predicting values.
---------------------------------------------------------------
В предыдущем видео вы увидели, как подготовить временные ряды к машинному обучению, выбирая данные окном. Вы видели код для создания очень простого набора данных и узнали, как разделить этот набор данных на признаки и метки, т.е., X и Y. В этом видео мы пройдёмся разберём всё содержимое блокнота с кодом. Для начала нужно, чтобы у вас был установлен TensorFlow 2.0. Чтобы проверить вашу версию, запустите этот блок кода. Он должен вывести 2.0.0-что-то ещё. В данном случае, я использую ночную сборку, отсюда -dev<код> на конце. Если вам нужна версия 2.0, её можно установить с помощью следующего кода. Tf-nightly-2.0-preview — версия для разработчиков, которую я только что упомянул, либо можно установить TF 2.0 с помощью pip install tenorflow, как здесь. Версия может отличаться от b1, т.к. к моменту записи этого видео для TensorFlow была выпущена бета 1. Сверьтесь со свежими инструкциями на tenorflow.org для установки продуктовой сборки. После того, как вы установили TensorFlow, можно запустить этот код. Сначала мы создадим простой набор данных, и это просто диапазон, содержащий 10 элементов от нуля до девяти. Как видите, мы вывели каждый из них на отдельной строке. Дальше мы разобьём набор данных на окна по 5 элементов, каждый раз делая сдвиг на один элемент. Мы видим, что это даёт нам на выходе сначала первые 5 элементов, потом вторые 5 элементов, затем третьи 5 элементов, и т. д. В конце набора данных, когда данных на 5 элементов не хватает, видно более короткие строки. Чтобы остались лишь блоки из пяти записей, мы установим для drop_reminder значение true. Запустив код, мы увидим, что наши данные выглядят так. Мы получили ровные наборы одинакового размера. TensorFlow любит, чтобы данные были в формате numpy. И мы можем легко их преобразовать, вызвав метод .numpy, и если вывести его результат, то мы видим, что теперь списки идут в квадратных скобках. Далее следует разделить данные на X и Y — признаки и метки. Мы возьмем последний столбец в качестве метки, и разделим списки, используя лямбда-функцию. Мы разделим данные с помощью [:-1], что даёт все столбцы, кроме последнего, и [-1:], что даёт только последний столбец. Теперь мы видим, что у нас есть наборы по четыре элемента и по одному элементу. Помните, что [-1:] обозначает последнее значение в списке, а [:-1] означает всё, кроме последнего значения. Таким образом, мы видим, например, 0, 1, 2, 3 и 1, 2, 3, 4 — до точки разделения. Дальше, конечно, нужно перемешать данные. И это можно сделать, используя метод shuffle. Он помогает нам переупорядочить данные так, чтобы модель случайно не стала зависеть от порядка в данных. Если запускать этот блок многократно, данные всякий раз будут идти в другом порядке, т.к. этот порядок случайный. И наконец, подготовка пакетов. Установив размер пакета 2, мы группируем данные по два X и два Y за раз. Например, как мы уже видели, если x = [0, 1, 2, 3], то мы видим, что соответствующий y = 4, а если x = [5, 6, 7, 8], тогда y = 9. Итак, это рабочий блокнот с кодом, который разбивает временной ряд на окна. Попробуйте его самостоятельно, и когда вы освоитесь в этом коде, переходите к следующему видео. Там вы перейдёте к сезонному набору данных, который уже использовали раньше, и пользуясь данным методом разбиения на окна, вы посмотрите, как задать X и Y так, чтобы можно было подать их на вход нейросети и посмотреть, как она справится с прогнозированием значений.

5(w2)-Single layer neural network notebook (Lab 2): (18.MLg_4c)

The next lectures will show how you can feed windowed datasets to a single neural network. You can use the notebook here to follow along or you can run it after the screencast.
C4_W2_Lab_2_single_layer_NN.ipynb
Ungraded Lab: Training a Single Layer Neural Network with Time Series Data
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W2/ungraded_labs/C4_W2_Lab_2_single_layer_NN.ipynb
---------------------------------------------------------------

6(w2)-video4: Feeding windowed dataset into neural network (18.MLg_4c)

In the last videos you saw how to prepare time series data for machine learning by creating a window dataset where the previous n values could be seen as the input features are x. And the current value with any time stamp is the output label or the y. It would then look a little bit like this. With a number of input values on x, typically called a window on the data. You saw in the previous videos how to use the tools in tensor flow datasets to create these windows. This week you'll adapt that code to feed a neural network and then train it on the data. So let's start with this function that will call a windows dataset. It will take in a data series along with the parameters for the size of the window that we want. The size of the batches to use when training, and the size of the shuffle buffer, which determines how the data will be shuffled. The first step will be to create a dataset from the series using a tf.data dataset. And we'll pass the series to it using its from_tensor_slices method. We will then use the window method of the dataset based on our window_size to slice the data up into the appropriate windows. Each one being shifted by one time set. We'll keep them all the same size by setting drop remainder to true. We then flatten the data out to make it easier to work with. And it will be flattened into chunks in the size of our window_size + 1. Once it's flattened, it's easy to shuffle it. You call a shuffle and you pass it the shuffle buffer. Using a shuffle buffer speeds things up a bit. So for example, if you have 100,000 items in your dataset, but you set the buffer to a thousand. It will just fill the buffer with the first thousand elements, pick one of them at random. And then it will replace that with the 1,000 and first element before randomly picking again, and so on. This way with super large datasets, the random element choosing can choose from a smaller number which effectively speeds things up. The shuffled dataset is then split into the xs, which is all of the elements except the last, and the y which is the last element. It's then batched into the selected batch size and returned.
---------------------------------------------------------------
В прошлых видео вы посмотрели, как подготовить данные временных рядов для машинного обучения, создав набор данных на основе окон, где предыдущие n значений можно взять в качестве входных признаков — X, а текущее значение в любой момент времени служит выходной меткой, или Y. Это выглядит примерно так, где количество входных значений в X называется окном данных. Вы видели в предыдущих видео, как использовать инструменты tensorflow.datasets для создания таких окон. На этой неделе вы адаптируете этот код для ввода данных в нейросеть и обучения её на этих данных. Итак, давайте начнём с этой функции, которую мы назовём windowed_dataset. Она принимает на вход временной ряд, а также параметры: нужный нам размер окна, размер пакета для обучения, а также размер буфер для перемешивания, определяющий, как данные будут перемешаны. Первым шагом будет создание набора данных на основе ряда с использованием tf.data.Dataset. Мы передадим в него ряд, используя метод from_tensor_slices. Затем мы используем метод dataset.window, основываясь на window_size, чтобы нарезать данные на соответствующие окна, каждое из которых сдвинуто на один шаг по времени. Мы создадим их все одного размера, задав drop_remainder=True. Затем мы сделаем данные плоскими, чтобы с ними было проще работать. И они будут собраны в группы размером с наше window_size + 1. Когда они стали плоскими, их легко перемешать. Вы вызываете метод shuffle, передавая параметр shuffle_buffer. Использование этого параметра немного ускоряет работу. Так, например, если у вас в наборе 100 000 элементов, а вы установите буфер, равный 1000, то просто заполнит буфер первой тысячей элементов, возьмёт один из них наугад, затем заменит его 1001-м элементом, случайно выберет ещё один, и так далее. Тем самым, для очень больших наборов данных можно выбирать элемент случайно из меньшего числа, что существенно ускоряет дело. Перемешанный набор данных затем разделяется на X, т.е., все элементы, кроме последнего, — и Y, которым будет последний элемент. Затем данные раскладываются по пакетам заданного размера и возвращаются.

7(w2)-video5: Single layer neural network (18.MLg_4c)

Now that we have a window datasets, we can start training neural networks with it. Let's start with a super simple one that's effectively a linear regression. We'll measure its accuracy, and then we'll work from there to improve that. Before we can do a training, we have to split our dataset into training and validation sets. Here's the code to do that at time step 1000. We can see that the training data is the subset of the series called x train up to the split time. Here's the code to do a simple linear regression. Let's look at it line by line. We'll start by setting up all the constants that we want to pass to the window dataset function. These include the window size on the data, the batch size that we want for training, and the size of the shuffled buffer as we've just discussed. Then we'll create our dataset. We'll do this by taking our series, and in the notebook that you'll go through later, you'll create the same synthetic series as you did in week one. You'll pass it your series along what your desired window size, batch size, and shuffled buffer size, and it will give you back a formatted datasets that you could use for training. I'm then going to create a single dense layer with its input shape being the window size. For linear regression, that's all you need. I'm using this approach. By passing the layer to a variable called L0, because later I'm want to print out its learned weights, and it's a lot easier for me to do that if I have a variable to refer to the layer for that. Then I simply define my model as a sequential containing the sole layer just like this. Now I'll compile and fit my model with this code. I'll use the mean squared error loss function by setting loss to MSE, and my optimizer will use Stochastic Gradient Descent. I'd use this methodology instead of the raw string, so I can set parameters on it to initialize it such as the learning rate and the momentum. Experiment with different values here to see if you can get your model to converge more quickly or more accurately. Next you can fit your model by just passing it the dataset, which has already been preformatted with the x and y values. I'm going to run for a 100 epochs here. Ignoring the epoch but epoch output by setting verbose to zero. Once it's done training, you can actually inspect the different weights with this code. Remember earlier when we referred to the layer with a variable called L 0? Well, here's where that's useful. The output will look like this. If you inspect it closely, you will see that the first array has 20 values in it, and the secondary has only one value. This is because the network has learned a linear regression to fit the values as best as they can. So each of the values in the first array can be seen as the weights for the 20 values in x, and the value for the second array is the b value.
---------------------------------------------------------------
Теперь, когда у нас есть оконный набор данных, можно приступить к обучению нейросети. Давайте начнем со сверхпростой сети, — фактически, с линейной регрессии. Мы измерим её точность, а затем поработаем над её улучшением. Перед обучением нам нужно разделить набор данных на обучающую и валидационную выборки. Вот код, выполняющий такое разбиение относительно момента времени 1000. Мы видим, что обучающая выборка — это подмножество ряда до момента времени split_time, и называется x_train. Вот код для модели простой линейной регрессии. Давайте разберём его построчно. Мы начинаем с определения всех констант, которые хотим передать в функцию windowed_dataset. Сюда входят размер окна данных, размер пакета, при котором мы хотим обучать сеть, и размер буфера перемешивания, который мы только что обсуждали. Затем мы создаём наши выборки. Мы сделаем это, взяв наш ряд, а в блокноте, который вы увидите позже, вы создадите тот же синтетический ряд, который уже создавали на первой неделе. Нужно передать этот ряд, а также размер окна, размер пакета и размер буфера перемешивания, — и функция вернёт вам отформатированный набор данных, который можно использовать для обучения. Далее я создаю один полносвязный слой со входом, равным размеру окна. Для линейной регрессии нам больше ничего не требуется. Я делаю это вот так, передавая слой в переменную с именем l0, т.к. я хочу позже вывести веса, которые слой выучил, а это будет намного легче сделать, если у меня будет переменная, на которую можно ссылаться для обращения к слою. Далее я просто определяю модель как последовательную и содержащую единственный слой, вот таким образом. Теперь я компилирую модель и запускаю её обучение. Я использую среднеквадратичную ошибку в качестве функции потерь, установив параметр loss = "mse", а мой оптимизатор будет использовать стохастический градиентный спуск (SGD). Я использую этот способ [выбора оптимизатора] вместо строкового параметра, чтобы можно было задать ему параметры инициализации, такие как скорость обучения lr и импульс momentum. Поэкспериментируйте с различными значениями этих параметров, чтобы посмотреть, удастся ли вам заставить вашу модель сходиться быстрее или точнее. Дальше вы запускаете обучение модели, просто передав ей набор данных, который уже отформатирован и содержит значения X и Y. Я собираюсь обучать модель в течение 100 эпох и ничего не выводить между эпохами, установив для этого verbose=0. Как только обучение закончилось, вы можете изучить веса сети с помощью данного кода. Помните, мы ранее сохранили ссылку на слой в переменную с именем l0? Именно здесь она и пригодилась. Результат будет выглядеть примерно так. Если вы внимательно его изучите, то увидите, что в первом массиве содержится 20 значений, а во втором — только одно. Это потому что сеть обучила веса линейной регрессии, чтобы как можно лучше отвечать заданным значениям. Таким образом, значения из первого массива будут весами для 20 значений вектора x, а значение во втором массиве — это b.

8(w2)-video6: Machine learning on time windows (18.MLg_4c)

So if you think back to this diagram and you consider the input window to be 20 values wide, then let's call them x0, x1, x2, etc, all the way up to x19. But let's be clear. That's not the value on the horizontal axis which is commonly called the x-axis, it's the value of the time series at that point on the horizontal axis. So the value at time t0, which is 20 steps before the current value is called x0, and t1 is called x1, etc. Similarly, for the output, which we would then consider to be the value at the current time to be the y.
---------------------------------------------------------------
Если вернуться к этой диаграмме, и взять входное окно шириной в 20 значений — давайте назовём их x0, x1, x2, ..., x19. Но давайте проясним. xi — это не значение на горизонтальной оси, которую обычно называют осью х, — это значение временного ряда в этой точке на горизонтальной оси. То есть, значение в момент времени t0, за 20 шагов до текущего значения, — называется x0, значение в t1 — это x1, и т.д. А выходное значение, которое мы считаем значением на текущий момент времени, — мы обозначаем за y.

9(w2)-video7: Prediction (18.MLg_4c)

So now, if we look at the values again and see that these are the weights for the values at that particular timestamp and b is the bias, we can do a standard linear regression like this to predict the value of y at any step by multiplying out the x values by the weights and then adding the bias. So for example, if I take 20 items in my series and print them out, I can see the 20x values. If I want to predict them, I can pass that series into my model to get a prediction. The NumPy new axis then just reshapes it to the input dimension that's used by the model. The output will look like this. The top array is the 20 values that provide the input to our model and the bottom is the predicted value back from the model. So we've trained our model to say that when it sees 20 values like this, the predicted next value is 49.08478. So if we want to plot our forecasts for every point on the time-series relative to the 20 points before it where our window size was 20, we can write code like this. We create an empty list of forecasts and then iterate over the series taking slices and window size, predicting them, and adding the results to the forecast list. We had split our time series into training and testing sense taking everything before a certain time is training and the rest is validation. So we'll just take the forecasts after the split time and load them into a NuimPy array for charting. That chart looks like this with the actual values in blue and the predicted ones in orange. You can see that our predictions look pretty good and getting them was relatively simple in comparison with all the statistical gymnastics that we had to do in the last videos. So let's measure the mean absolute error as we've done before, and we can see that we're in a similar ballpark to where we were with a complex analysis that we did previously. Now that's just using a single layer in a neural network to calculate a linear regression. Let's see if we could do better with a fully-connected DNN next. Before you get to that, we'll go through the workbook for this lesson to ensure that you understand everything we've done up to now. The next video will be a screencast of going through that and then you'll work on the DNN after that.
---------------------------------------------------------------
Так что теперь, если снова посмотреть на значения, и увидеть, что это веса для значений в конкретный момент времени, а b — общее смещение, то можно построить стандартную линейную регрессию, вроде этой, чтобы предсказывать значение у на любой момент времени, перемножая значения х с этими весами, а затем добавляя смещение. Так, если я возьму для примера 20 элементов из моего ряда, и выведу их на экран, то увижу 20 значений из x. Чтобы их предсказать, можно передать этот ряд в мою модель, получая прогноз. np.newaxis просто изменяет форму массива так, чтобы его размерность соответствовала входу модели. Результат будет выглядеть вот так. Верхний массив — это 20 значений которые обеспечивают вход для нашей модели, а нижний — предсказанное значение, которое вернула модель. Итак, мы обучили нашу модель при виде 20 подобных значений давать прогноз, что следующее значение составляет 49,08478. И если нам нужно построить прогноз для каждой точки временного ряда, основываясь на 20 предшествующих значениях, где 20 — это наш размер окна, — то для этого можно написать подобный код. Создаем пустой список для прогнозов, а затем проходим в цикле по ряду, вырезая данные под размер окна, прогнозируя для них результат и добавляя его к списку прогнозов. Мы разделили наш временной ряд на обучающую и тестовую выборки, взяв все значения до определённого момента в качестве обучающей выборки, а остальное — валидационной. Итак, возьмём прогнозы после точки разделения и загрузим их в массив numpy для построения графика. Этот график выглядит вот так, здесь реальные данные — голубого цвета, а предсказанные — оранжевого. Видно, что наши прогнозы выглядят довольно хорошо, и получать их было относительно просто, по сравнению со всеми теми статистическими упражнениями, которые мы делали в предыдущих видео. Давайте измерим среднюю абсолютную ошибку, как мы уже делали раньше, и увидим, что мы примерно в одной весовой категории с тем сложным анализом, который мы делали раньше. Это мы использовали лишь один слой нейросети для вычисления линейной регрессии. Давайте далее посмотрим, можно ли добиться большего с полносвязной DNN. Прежде чем переходить к ней, пройдёмся по блокноту для нынешнего урока, чтобы убедиться, что вы поняли всё, что мы уже успели проделать. В следующем видео вы увидите, как это происходит, а затем уже начнёте работать над DNN.

10(w2)-video8: More on single layer neural network (18.MLg_4c)

In the last video, you saw how to write code to get a machine learned linear regression model of the time-series data. In this video, I'll step you through the notebook with all the code and then you can try it out for yourself. Next we'll run the code for all the helper functions that set up a data series as well as creating the data series itself. At the bottom of this code section, you'll see the code for setting up the series, splitting it into training and validation, and then setting up the constants to use for window size, batch size and all that. Now you can create the helper function for the window dataset as we saw in the previous video. Now we'll create our model by first getting a window dataset from the training data which as you may remember, was split off from the main set. We'll then define the model, compile it, and fit it to the data that we have, when it's done it will print out the layer weights. You can see the layer weights which provide the coefficients for the x values and the linear regression, as well as the bias value for their regression here. We got this by calling the get weights method on the layer. We can now plot the predictions for each of the elements in the validation split of the series, the predictions or an orange and the actual values are in blue. Finally, we can measure the mean absolute error between the valid data and the predicted results. Do note that you might see different values here, and in particular as you swap between notebooks, they might change drastically. Remember that the series has a random elements in it with the noise and as such measuring error in one notebook against another may not be the most accurate way because the noise will change. So don't worry if sometimes you see slightly larger values if you were expecting smaller ones. Next we'll take a look at using a deep neural network to predict on this data.
---------------------------------------------------------------
В предыдущем видео вы видели, как написать код обучения модели линейной регрессии для временного ряда. В этом видео мы пройдёмся пошагово по блокноту со всем этим кодом, а затем вы сможете попробовать всё сами. Как и раньше, проверьте, что у вас есть TensorFlow 2.0 для работы с этим кодом. Если у вас его нет, вы можете установить ночную версию или последовать инструкциям на TensorFlow.org для установки современной версии. Далее мы запустим код, содержащий вспомогательные функции, которые обрабатывают или даже создают временные ряды. В нижней части этого блока кода вы найдёте код для организации рядов: разбиения данных на обучающую и валидационную выборки, а затем задаются значения констант для размера окна, размера пакета и прочего. Теперь можно создать вспомогательную функцию для построения оконного набора данных, который мы видели в предыдущем видео. Теперь создадим нашу модель — сначала получим оконный набор данных из обучающих данных, которые, как вы, наверное, помните, были отрезаны от общего набора данных. Затем мы определим модель, скомпилируем её и запустим обучение на имеющихся данных. Когда оно завершится, то выведет веса слоя. Вы видите веса слоя, предоставляющие коэффициенты для значений х в линейной регрессии, а также значение смещения для этой регрессии. Мы получили их, вызвав у слоя метод get_weights. Теперь мы можем вывести на график прогнозы для каждого из элементов валидационной выборки: предсказания — оранжевые, а реальные значения — голубые. Наконец, мы можем измерить среднюю абсолютную ошибку между реальными значениями и предсказанными результатами. Обратите внимание, что у вас это значение может варьироваться, в частности, оно может сильно меняться при переключении между блокнотами. Помните, что ряд несёт элемент случайности в виде шума, и измерение ошибки в одном блокноте и сравнение её с другим может не слишком совпадать, потому что шум будет отличаться. Так что не волнуйтесь, если иногда заметите несколько более высокие значения, хотя ожидали меньших. Далее мы рассмотрим, как для предсказания этих данных использовать глубокую нейронную сеть.

11(w2)-Deep neural network notebook (Lab 3): (18.MLg_4c)

The last section for this week will demonstrate using multi-layer neural networks and you can use the notebook here as reference for the upcoming videos.
Ungraded Lab: Training a Deep Neural Network with Time Series Data
C4_W2_Lab_3_deep_NN.ipynb
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W2/ungraded_labs/C4_W2_Lab_3_deep_NN.ipynb#scrollTo=dxFGlX1S53mg
---------------------------------------------------------------

12(w2)-video9: Deep neural network training, tuning and prediction (18.MLg_4c)

Okay, so this week you've been looking at machine learning for predicting the next value in a sequence. You've learned how to break your data down into window chunks that you could train on, and then you saw a simple single layer neural network that gave you what was effectively a linear regression. Now let's take that to the next step with a DNN to see if we can improve our model accuracy. It's not that much different from the linear regression model we saw earlier. And this is a relatively simple deep neural network that has three layers. So let's unpack it line by line. First we'll have to get a data set which will generate by passing in x_train data, along with the desired window size, batch size, and shuffle buffer size. We'll then define the model. Let's keep it simple with three layers of 10, 10, and 1 neurons. The input shape is the size of the window and we'll activate each layer using a relu. We'll then compile the model as before with a mean squared error loss function and stochastic gradient descent optimizer. Finally, we'll fit the model over 100 epochs, and after a few seconds of training, we'll see results that look like this. It's pretty good still. And when we calculate the mean absolute error, we're lower than we were earlier, so it's a step in the right direction. But it's also a somewhat a stab in the dark, particularly with the optimizer function. Wouldn't it be nice if we could pick the optimal learning rate instead of the one that we chose? We might learn more efficiently and build a better model. Now let's look at a technique for that that uses callbacks that you used way back in the first course. So here's a code for the previous neural network. But I've added a callback to tweak the learning rate using a learning rate scheduler. You can see that code here. This will be called at the callback at the end of each epoch. What it will do is change the learning rates to a value based on the epoch number. So in epoch 1, it is 1 times 10 to the -8 times 10 to the power of 1 over 20. And by the time we reach the 100 epoch, it'll be 1 times 10 to the -8 times 10 to the power of 5, and that's 100 over 20. This will happen on each callback because we set it in the callbacks parameter of model.fit(). After training with this, we can then plot the last per epoch against the learning rate per epoch by using this code, and we'll see a chart like this. The y-axis shows us the loss for that epoch and the x-axis shows us the learning rate. We can then try to pick the lowest point of the curve where it's still relatively stable like this, and that's right around 7 times 10 to the -6. So let's set that to be our learning rate and then we'll retrain. So here's the same neural network code, and we've updated the learning rate, so we'll also train it for a bit longer. Let's check the results after training for 500 epochs. Here's the codes to plot out the loss that was calculated during the training, and it will give us a chart like this. Which upon first inspection looks like we're probably wasting our time training beyond maybe only 10 epochs, but it's somewhat skewed by the fact that the earlier losses were so high. If we cropped them off and plot the loss for epochs after number 10 with code like this, then the chart will tell us a different story. We can see that the loss was continuing to decrease even after 500 epochs. And that shows that our network is learning very well indeed. And the results of the predictions overlaid against the originals looks like this. And the mean absolute error across the results is significantly lower than earlier. I'll take you through a screencast of this code in action in the next video. Using a very simple DNN, we've improved our results very nicely. But it's still just a DNN, there's no sequencing taken into account, and in a time series like this, the values that are immediately before a value are more likely to impact it than those further in the past. And that's the perfect set up to use RNNs like we had in the natural language course. Now we'll look at that next week, but first, let's dig into this code.
---------------------------------------------------------------
На этой неделе вы посмотрели, как применять машинное обучение для прогнозирования следующих значений в последовательности. Вы узнали, как разбить ваши данные на окна для обучения на них, а затем увидели простую однослойную нейронную сеть, которая фактически решала задачу линейной регрессии. Теперь давайте пойдём дальше: возьмём DNN и посмотрим, удастся ли нам при этом улучшить точность нашей модели. Здесь мало отличий от ранее виденной модели линейной регрессии. Это относительно простая глубокая нейронная сеть, состоящая из трёх слоёв. Давайте разберём код построчно. Сначала нам нужен набор данных, который мы сгенерируем, передавая данные x_train вместе с желаемым размером окна, размером пакета и размером буфера для перемешивания. Затем определим модель. Пусть она будет простой: три слоя с 10, 10 и 1 нейронами. Вход сети совпадает с размером окна, и для активации каждого слоя мы используем relu. Затем скомпилируем модель, как и прежде, со среднеквадратичной ошибкой в качестве функцией потерь и стохастическим градиентным спуском в качестве оптимизатора. Наконец, запустим обучение модели в течение 100 эпох, и после нескольких секунд обучения получим результат, похожий на этот. Он довольно хорош. Вычислим среднюю абсолютную ошибку, — и она лучше, чем была раньше, так что это шаг в верном направлении. Но это похоже на тыканье вслепую, особенно при выборе оптимизационной функции. Разве не лучше было бы подбирать оптимальный темп обучения — вместо заданного нами значения? Тогда обучение шло бы эффективнее, давая более совершенную модель. Давайте рассмотрим подход к этой задаче, использующий обратные вызовы — вы их изучали очень давно, в первом курсе. Вот код для той же нейронной сети, но я добавил обратный вызов для подстройки скорости обучения при помощи LearningRateScheduler. Вот этот код. Он будет срабатывать при обратном вызове в конце каждой эпохи. И он будет менять скорость обучения, задавая новое значение, зависящее от номера эпохи. Таким образом, в первую эпоху это 1e-8 * 10**(1/20). А по достижении сотой эпохи, будет 1e-8 * 10**5, где 5 — это 100/20. Так будет при каждом обратном вызове, потому что мы передали эту функцию параметром callbacks метода model.fit. Обучив сеть таким образом, можно отобразить на графике потери в каждую из эпох соответственно скорости обучения в эту эпоху, что даст нам вот такой график. По оси ординат отображается значение функции потерь, а по оси абсцисс — темп обучения. Затем можно выбрать такую нижнюю точку графика, где функция ещё выглядит стабильно, как вот здесь — это примерно 7 на 10 в степени -6. Давайте установим такую скорость обучения и повторно обучим модель. Итак, вот код для той же нейросети, но мы изменили темп обучения, так что обучение будет идти чуть дольше. Давайте посмотрим результаты после обучения в течение 500 эпох. Вот код для вывода графика функции потерь, вычисленной во время обучения, и он даст нам примерно такой график. На первый взгляд выглядит, как будто мы зря тратим время, продолжая обучение после первых, скажем, 10 эпох, но картина искажается из-за того, что в начале потери были очень высоки. Если мы обрежем их и построим график функции потерь для эпох после десятой при помощи такого кода, то график будет говорить уже совсем другое. Мы видим, что функция потерь продолжала падать даже после 500 эпох. И это показывает, что наша сеть действительно очень хорошо учится. А результаты прогнозов накладываются на реальные значения примерно таким образом. Средняя абсолютная ошибка по всем результатам значительно ниже, чем раньше. В следующем видео я подробно пройдусь по этому коду. Используя очень простую DNN, мы значительно улучшили наши результаты. Но это всё ещё простая DNN: она не принимает во внимание последовательности, а в подобных временных рядах значения, непосредственно предшествующие прогнозируемому, могут куда сильнее влиять на него, чем более старые значения. И это идеальные условия для использования РНС, с которыми мы знакомились на курсе обработки естественных языков. На следующей неделе мы их рассмотрим, а пока давайте углубимся в нынешний код.

13(w2)-video10: Deep neural network (18.MLg_4c)

In the previous video, we looked at training a deep neural network to learn, to predict the next value in a Windows sequence. We also looked at some basic hyper parameter tuning to pick a good learning rate for the gradient descent, which then allowed us to further improve the model. In this video, we'll wrap up this week by going through the workbook that shows you how to do all of that. Running this block will set up the data series and all the constants for the Window size and all that. This code will create the Window dataset as before. And here is our DNN where we have three layers in a sequential. The first has ten neurons activated by relu. The second is the same, and the third is a single dense giving us back the predicted value. We'll compile it with means squared error loss and stochastic gradient descent as an optimizer. After 100 epochs it's done, and we can plot the forecast versus the data. Then we can print the mean absolute error. Don't worry if you get a different value, remember there's going to be some random noise in the dataset. If we run this code block we'll retrain over 100 epochs, but we'll use the code back to call the learning rate scheduler, which will then adjust the learning rate over each epoch. When it's done we can then plot the results of the loss against the learning rates. We can then inspect the lower part of the curve before it gets unstable. And we'll come up with the value. In this case it looks to be about two notches to the left of 10 to the minus 5. So I'll say it's 8 times 10 to the minus 6, or thereabouts. I'll then retrain and this time I'll do it for 500 epochs with that learning rate when it's done, I can then plot the loss against the epoch. So we can see how the loss progressed over training time. We can see that it fell sharply and then flattened out. But agin if we remove the first ten epochs, we'll see the latter ones more clearly and it still shows the loss smoothly decreasing at 500 epochs. So it's actually still learning. Let's now plot the forecast against the data and we can see that the prediction still look pretty good. And when we print out the value of the mean absolute error we have improved even further over the earlier value. So that wraps up this week. Go through the workbook yourself and experiment with different neural network definitions, changing around the layers and stuff like that to see if If we can make it even better. Next week we're going to take this to the next level by using neural network types that were current neural networks which have sequencing capabilities built-in. I'll see you there.
---------------------------------------------------------------
В предыдущем видео мы посмотрели, как обучить глубокую нейросеть предсказывать следующее значение в оконной последовательности. Мы также рассмотрели некоторую базовую подстройку гиперпараметров для выбора хорошего темпа обучения при градиентном спуске, что позволило ещё улучшить модель. Этим видео мы завершим неделю разбором блокнота, который покажет вам, как всё это сделать. Запустим этот код, чтобы посмотреть текущую версию TensorFlow. Как и прежде, если вы используете версию старее 2.0, то увидите это здесь. Используйте предыдущую этой ячейку кода, чтобы установить свежую версию TensorFlow или ночную сборку, как у меня. Запуск этого блока подготовит данные и все константы: для размера окна и т.п. Этот код создаст оконный набор данных, как и раньше. А вот наша DNN, в которой три последовательных слоя. Первый имеет десять нейронов с функцией активации relu. Второй слой такой же, а третий — полносвязный слой с одним нейроном, возвращающий предсказанное значение. Скомпилируем модель со среднеквадратичной ошибкой в качестве функции потерь и стохастическим градиентным спуском в качестве оптимизатора. После 100 эпох обучение завершается, и мы можем вывести на график прогноз и реальные данные. А затем вывести среднюю абсолютную ошибку. Не волнуйтесь, если вы получите другое значение: помните, что в наборе данных есть случайный шум. Если выполнить этот блок кода, мы запустим обучение заново в течение 100 эпох, только уже с использованием обратного вызова LearningRateScheduler, который будет менять темп обучения после каждой эпохи. Когда обучение закончится, мы можем построить график зависимости потерь от темпа обучения. Затем изучим нижнюю часть кривой до той точки, где она становится нестабильной, и найдём нужное значение. В данном случае, оно будет примерно на 2 деления левее 1e-5. То есть, 8e-6, или около того. Затем обучим заново, в этот раз — на протяжении 500 эпох, с выбранной скоростью обучения. По завершении построим график функции потерь в зависимости от эпохи, чтобы посмотреть, как потери менялись по мере обучения. Мы видим, что кривая резко упала, а затем вышла в горизонталь. Но если мы снова уберём первые 10 эпох, то сможем лучше разглядеть последующие, и это покажет, что величина потерь плавно снижается даже после 500 эпох. То есть, модель всё ещё учится. Давайте теперь выведем прогнозы в сравнении с реальными данными. Как видим, прогноз всё ещё выглядит очень хорошо. А когда мы выведем значение средней абсолютной ошибки, окажется, что мы ещё сильнее улучшили предыдущий результат. На этом неделя завершается. Самостоятельно пройдитесь по блокноту и поэкспериментируйте с различными моделями нейросетей: изменяйте слои и прочие параметры, чтобы посмотреть, можно ли ещё улучшить результат. На следующей неделе мы выйдем на следующий уровень — используем рекуррентные виды нейросетей, в которых изначально заложена способность работать с последовательностями. До скорых встреч!

14(w2)- Week 2 Quiz: (18.MLg_4c)

1) What is a windowed dataset?:
1. A fixed-size subset of a time series (+)
2. The time series aligned to a fixed shape
3. There's no such thing
4. A consistent set of subsets of a time series
2) What does 'drop_remainder=True' do?:
1. It ensures that all data is used
2. It ensures that all rows in the data window are the same length by cropping data (+)
3. It ensures that the data is all the same shape
4. It ensures that all rows in the data window are the same length by adding data
3) What's the correct line of code to split an n column window into n-1 columns for features and 1 column for a label?:
1. dataset=dataset.map(lambda window:(window[n-1], window[1]))
2. dataset=dataset.map(lambda window:(window[:-1], window[-1:])) (+)
3. dataset=dataset.map(lambda window:(window[-1:], window[:-1]))
4. dataset=dataset.map(lambda window:(window[n], window[1]))
4) What does MSE stand for?:
1. Mean Series error
2. Mean Second error
3. Mean Squared error (+)
4. Mean Slight error
5) What does MAE stand for?:
1. Mean Average error
2. Mean Advanced error
3. Mean Absolute error (+)
4. Mean Active error
6) If time values are in time[], series values are in series[] and we want to split the series into training and validation at time split_time, what is the correct code?:
1.: time_train = time[split_time]
x_train = series[split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
2.: time_train = time[:split_time] (-)
x_train = series[:split_time]
time_valid = time[split_time]
x_valid = series[split_time]
3.: time_train = time[split_time]
x_train = series[split_time]
time_valid = time[split_time]
x_valid = series[split_time]
4.: time_train = time[:split_time] (+)
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
7) If you want to inspect the learned parameters in a layer after training, what's a good technique to use?:
1. Assign a variable to the layer and add it to the model using that variable, Inspect its properties after training. (+)
2. Decompile the model and inspect the output for that layer
3. Run the model with unit data and inspect the output for that layer
4. Iterate through the layers dataset of the model to find the layer you want
8) How do you set the learning rate of the SGD optimizer?:
1. Use the Rate property
2. You can't set it
3. Use the learning_rate property (+)
4. Use the RateOfLearning property
9) If you want to amend the learning rate of the optimizer on the fly, after each epoch. What do you do?:
1. Use a LearningRateScheduler and pass it as a parameter to a callback (-)
2. Callback to a custom function and change the SGD property
3. Use a LearningRateScheduler object in the callbacks namespace and assign that to the callback (+)
4. You can't set it

15(w2)- Week 2 Wrap up: (18.MLg_4c)

You've now explored time series data and seen how to split it into training and validation sets for training a DNN.
But sequence data tends to work better with RNNs. So next week, you're going to look at training a model using RNNs and LSTMs on this data to see what happens.
---------------------------------------------------------------
Теперь вы изучили данные временных рядов и увидели, как разделить их на наборы для обучения и проверки для обучения DNN.
Но данные последовательности, как правило, лучше работают с RNN. Итак, на следующей неделе вы рассмотрите обучение модели с использованием RNN и LSTM на этих данных, чтобы увидеть, что произойдет.

16(w2)- Lecture Notes Week 2: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

17(w2)- Programming Assignment: Forecasting Using Neural Networks: (18.MLg_4c)

Week 2: Predicting time series
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/programming/wiD05/forecasting-using-neural-networks/lab

NEXT week_3 (18.MLg_4c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w3)Recurrent Neural Networks for Time Series (18.MLg_4c)

(Рекуррентные нейронные сети для временных рядов)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 17 minutes
Self-study: 1h 26 min
Graded tasks (Tasks to be assessed): 2

(w3) Content (18.MLg_4c)

1.
2.
3.
4.

(w3) Introduction: (18.MLg_4c)

Recurrent Neural networks and Long Short Term Memory networks are really useful to classify and predict on sequential data. This week we'll explore using them with time series...
---------------------------------------------------------------
Рекуррентные нейронные сети и сети долговременной памяти действительно полезны для классификации и прогнозирования последовательных данных. На этой неделе мы рассмотрим их использование с временными рядами...

1(w3)-video1: Week 3 - A conversation with Andrew Ng (18.MLg_4c)

Welcome to week three. In this week, you get to apply RNNs and LSTMs to the time sequence data. Last week you'd applied DNNs to this data. But time series is temporal data, seems like you should be applying a sequence model, like an RNN or an LCM to that. So that's what you do this week. >> Yes, so it's, if you remember in the previous courses, we did natural language processing. And we learned a lot about RNNs and LSTMs there. And how things like the state vector and the cell state in these allow you to maintain context across a series. And with something like a time series data, if you're looking at maybe a 30-day window, or a 30 period window, the likelihood in some time series of data closer to your predictive date, having a bigger impact on data further away, it's there, right? There is a higher likelihood for that. So being able to use RNNs and LSTMs might factor that in to our data to give us a much more accurate prediction. >> Yeah, that's right, looking over a much bigger windows and carrying context from far away. >> Yeah, yeah, exactly, and you know my old favorite LSTMs, and the way they have that cell state, that allows you, we should call it L state, after me. [LAUGH] And the way you have that cell state that allows you to carry context across a long learning process. And I think in some time series data, that would be a really large impact. So for example, like financial data, today's closing price has probably got a bigger impact on tomorrow's closing price than the closing price from 30 days ago, or 60 days ago, or 90 days ago. So being able to use recurrent networks and LSTMs I think it will help us be able to be much more accurate in predicting seasonal data. >> Yeah, cool, and one of the fun things that we'll see this week as well is Lambda layers. >> Lambda layers, yeah. So as a coder, Lambda layers give me comfort. Because sometimes one of the hardest things for me, when I first started doing neural networks was, I write all this code for pre-processing and I write all this code for post-processing. And then I define a neural network and it does all this magic inside a neural network. But I may not have control over what's going on in there. >> It just does whatever it wants to do. >> Or whatever it's been designed to do [LAUGH]. And so, but in Tensorflow and with Keras, Lambda layers allow us to write effectively an arbitrary piece of code as a layer in the neural network. >> So rather than, for example, scaling your data with an explicit pre-processing step and then feeding that data into the neural network, you can instead have a Lambda layer. Basically a Lambda function, an unnamed function, but implemented as a layer in the neural network that resend the data, scales it. And now that pre-processing step is no longer a separate and distinct step, it's part of the neural network. >> So as a programmer that just gives me a lot more comfort, having that kind of control. And it makes it even more fun to be able to build this kind of stuff. >> Yeah, so in this week, you get to apply our RNNs and LCMs to the sequence data. And, as one of the fun features of Tensorflow you learn as well, you also get to implement Lambda layers. Please go on to the next video.
---------------------------------------------------------------
Добро пожаловать на третью неделю. На этой неделе вы научитесь применять РНС и LSTM к временным рядам. На прошлой неделе вы применяли к этим данным глубокую нейросеть, но временные ряды разворачиваются во времени, и к ним лучше применять последовательную модель, такую как РНС или LSTM. Вот этим вы и займётесь на этой неделе. Да, это так. Если помните, на предыдущих курсах мы занимались обработкой естественных языков. И мы многое тогда узнали о РНС и LSTM. И как в них вектор состояния и ячейки памяти позволяют удерживать контекст на протяжении всей последовательности. Когда у нас данные, подобные временному ряду, то при работе с 30-дневным окном, или окном на 30 отсчётов — есть вероятность, что в некоторых рядах данные, лежащие ближе к дате, на которую нужен прогноз, влияют на фактическое значение сильнее, чем более давние данные, верно? Такой расклад вероятнее. И здесь возможность использовать РНС и LSTM может привести к тому, что для таких данных мы получим более точный прогноз. Да, верно, глядя через гораздо большие окна и передавая контекст на большие расстояния. Да, точно, и вам знакомы мои старые любимые LSTM, и то, как в них устроено состояние ячейки состояния (cell state), — может, назвать её L-state, в честь меня? [СМЕХ] Реализация вектора состояний позволяет вам долго удерживать контекст в процессе обучения. И я думаю, что для некоторых временных рядов это должно действительно сильно проявляться. Например, в финансовых данных: сегодняшняя цена закрытия, вероятно, больше влияет на завтрашнюю цену закрытия, чем цена 30 дней назад, или 60, или 90. Так что, думаю, использование рекуррентных сетей и LSTM поможет нам быть куда точнее при прогнозировании сезонных данных. Да, здорово, и среди прочего интересного, на этой неделе мы рассмотрим лямбда-слои. Лямбда-слои, да. Как программисту, лямбда-слои облегчают мне жизнь, ведь, на мой взгляд, одна из самых сложных вещей была в том, что при первых своих пробах с нейросетями я писал кучу кода для предобработки и кучу кода код для постобработки. А затем я строил нейросеть, и внутри неё происходила вся вот эта магия, но у меня не было контроля над тем, что там происходит. Сеть просто делает, что хочет. Или то, для чего она создана. Но в Tensorflow и Keras лямбда-слои позволяют нам прописать практически произвольный кусок кода в качестве слоя нейронной сети. Так, например, вместо того, чтобы масштабировать данные явным образом на этапе предобработки, и затем отправлять их на вход нейросети, вы можете создать лямбда-слой — по сути, лямбда-функцию, анонимную функцию, — встроив её в качестве слоя в нейросеть, чтобы она загружала и масштабировала данные. И тогда предобработка — уже не отдельный независимый этап, а часть нейросети. И как программисту, мне так намного удобней — таким образом это контролировать. И возможность создавать такие штуки делает процесс интереснее. Итак, на этой неделе вы будете применять наши РНС и LSTM для временных рядов, а заодно изучите одну из самых любопытных возможностей TensorFlow — научитесь создавать лямбда-слои. Приглашаем вас перейти к следующему видео.

2(w3)-video2: Conceptual overview (18.MLg_4c)

In the last couple of weeks, you've looked at creating neural networks to forecast time-series data. You started with some simple analytical techniques, which you then extend it to using Machine Learning to do a simple regression. From there you use the DNN that you tweaked a bit to get an even better model. This week, we're going to look at RNNs for the task of prediction. A Recurrent Neural Network, or RNN is a neural network that contains recurrent layers. These are designed to sequentially processes sequence of inputs. RNNs are pretty flexible, able to process all kinds of sequences. As you saw in the previous course, they could've been used for predicting text. Here we'll use them to process the time series. This example, will build an RNN that contains two recurrent layers and a final dense layer, which will serve as the output. With an RNN, you can feed it in batches of sequences, and it will output a batch of forecasts, just like we did last week. One difference will be that the full input shape when using RNNs is three-dimensional. The first dimension will be the batch size, the second will be the timestamps, and the third is the dimensionality of the inputs at each time step. For example, if it's a univariate time series, this value will be one, for multivariate it'll be more. The models you've been using to date had two-dimensional inputs, the batch dimension was the first, and the second had all the input features. But before going further, let's dig into the RNN layers to see how they work. What it looks like there's lots of cells, there's actually only one, and it's used repeatedly to compute the outputs. In this diagram, it looks like there's lots of them, but I'm just using the same one being reused multiple times by the layer. At each time step, the memory cell takes the input value for that step. So for example, it is zero at time zero, and zero state input. It then calculates the output for that step, in this case Y0, and a state vector H0 that's fed into the next step. H0 is fed into the cell with X1 to produce Y1 and H1, which is then fed into the cell at the next step with X2 to produce Y2 and H2. These steps will continue until we reach the end of our input dimension, which in this case has 30 values. Now, this is what gives this type of architecture the name a recurrent neural network, because the values recur due to the output of the cell, a one-step being fed back into itself at the next time step. As we saw in the NLP course, this is really helpful in determining states. The location of a word in a sentence can determine it semantics. Similarly, for numeric series, things such as closer numbers in the series might have a greater impact than those further away from our target value.
---------------------------------------------------------------
В последние пару недель вы познакомились с тем, как создавать нейросеть для предсказания временных рядов. Вы начали с простых аналитических методов, которые потом расширили средствами машинного обучения, именно, простой регрессии. Потом перешли к глубоким нейросетям, которые вы подстраивали, чтобы чуть улучшить модель. На этой неделе мы рассмотрим применение РНС для прогнозирования. Рекуррентные Нейронные Сети, или РНС, — это нейросети, которые содержат рекуррентные слои. Они предназначены для последовательной обработки входной последовательности. РНС — довольно гибкие, и способны обрабатывать все виды последовательностей. Как вы видели в предыдущем курсе, их можно использовать для предсказания текста. Здесь мы будем использовать их для прогнозирования временных рядов. В этом примере мы построим РНС, которая содержит два рекуррентных слоя и последний полносвязный слой, который будет служить выходом. В РНС можно подавать на вход пакеты последовательностей, а она будет выдавать пакеты прогнозов, прямо как у нас было на прошлой неделе. Единственное отличие будет в том, что полная размерность входных данных при использовании РНС будет трёхмерной. Первым измерением будет размер пакета, вторым — отсчёты времени, а третьим — размерность входных данных в каждый отдельный момент времени. Например, если это одновариантный временной ряд, то его размерность будет равна 1, а для многовариантного она будет выше. У моделей, которые вы использовали раньше, вход был двумерный: размер пакета служил первым измерением, а вторым было число входных признаков. Но прежде чем идти дальше, давайте углубимся в слои РНС и посмотрим, как они работают. Они похожи на множество ячеек, которые, в действительности, являются единой ячейкой, которая используется раз за разом для вычисления выхода. На этой диаграмме кажется, будто их множество, но я просто использую одну и ту же ячейку, которую слой использует многократно. На каждом временном шаге ячейка памяти принимает входное значение этого шага, например, в нулевой момент времени это X0, а состояние входа равно 0. Затем сеть вычисляет свой выход для этого шага — в данном случае, Y0, а также вектор состояния H0, который передаётся следующему шагу. H0 подается в ячейку вместе с X1 для получения Y1 и H1, который (H1) затем подаётся в ячейку на следующем шаге вместе с X2, чтобы получить Y2 и H2. И так продолжается шаг за шагом, пока мы не достигнем конца входной последовательности, которая здесь состоит из 30 значений. Вот почему этот тип архитектуры называется рекуррентной нейросетью — потому что данные с выхода ячейки на одном шаге ячейка снова подаёт на свой же вход на следующем шаге. Как мы видели в курсе обработки естественных языков, это действительно полезно при выделении состояний. Положение слова в предложении может определять его семантику. Аналогично и для числовых рядов: более близкие значения в последовательности могут влиять сильнее, чем более отдалённые от нашего целевого значения.

3(w3)-RNN notebook (Lab 1): (18.MLg_4c)

In the next videos, Laurence will demonstrate using RNNs to build your predictive model. You can use the notebook here to follow along.
C4_W3_Lab_1_RNN.ipynb
Ungraded Lab: Using a Simple RNN for forecasting
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W3/ungraded_labs/C4_W3_Lab_1_RNN.ipynb#scrollTo=fO0xC1Cfp5-U
---------------------------------------------------------------

4(w3)-video3: Shape of the inputs to the RNN (18.MLg_4c)

Okay. We've mentioned the shape of the data and the batches that the data is split up into. It's important to take a look at that, and let's dig into that next. The inputs are three dimensional. So for example, if we have a window size of 30 timestamps and we're batching them in sizes of four, the shape will be 4 times 30 times 1, and each timestamp, the memory cell input will be a four by one matrix, like this. The cell will also take the input of the state matrix from the previous step. But of course in this case, in the first step, this will be zero. For subsequent ones, it'll be the output from the memory cell. But other than the state vector, the cell of course will output a Y value, which we can see here. If the memory cell is comprised of three neurons, then the output matrix will be four by three because the batch size coming in was four and the number of neurons is three. So the full output of the layer is three dimensional, in this case, 4 by 30 by 3. With four being the batch size, three being the number of units, and 30 being the number of overall steps. In a simple RNN, the state output H is just a copy of the output matrix Y. So for example, H_0 is a copy of Y_0, H_1 is a copy of Y_1, and so on. So at each timestamp, the memory cell gets both the current input and also the previous output. Now, in some cases, you might want to input a sequence, but you don't want to output on and you just want to get a single vector for each instance in the batch. This is typically called a sequence to vector RNN. But in reality, all you do is ignore all of the outputs, except the last one. When using Keras in TensorFlow, this is the default behavior. So if you want the recurrent layer to output a sequence, you have to specify returns sequences equals true when creating the layer. You'll need to do this when you stack one RNN layer on top of another.
---------------------------------------------------------------
Мы с вами упомянули размерность данных и пакеты, на которые разделены данные. Важно взглянуть на то, что это значит, и давайте следующим разберём этот вопрос. Входные данные являются трехмерными. Так, например, если у нас окно размером в 30 временных отсчётов, и мы собираем их в пакеты по 4, то размерность будет 4 x 30 x 1. На каждом шаге входом в ячейку памяти будет матрица 4 x 1, как здесь. Ячейка также будет принимать матрицу состояний с предыдущего шага. Но, конечно, здесь, на первом шаге, она будет нулевой. Для последующих шагов её значением будет выходное значение ячейки памяти. Но кроме вектора состояний ячейка, разумеется, будет выводить и значение Y, которое мы видим тут. Если ячейка памяти состоит из трёх нейронов, то выходная матрица будет 4 x 3, потому что размер подаваемого пакета равен 4, а нейронов — 3. Таким образом, полный выход слоя будет трёхмерным — в данном случае, 4 x 30 x 3, где 4 — размер пакета, 3 — количество нейронов, а 30 — общее количество шагов. В простой РНС выходной сигнал состояния H является просто копией выходной матрицы Y. Так, например, H0 будет копией Y0, H1 — копией Y1, и так далее. Так что на каждом шаге ячейка памяти получает как текущие входные значения, так и предыдущие выходные. Но в некоторых случаях может потребоваться подать на вход последовательность, ничего не отдавая на выход: нужно получить лишь один вектор для каждого входа в пакете. Это обычно называют РНС типа "многие к одному" (sequence-to-vector). По факту, вы просто игнорируете все выходы, кроме последнего. При использовании Keras в TensorFlow такое поведение используется по умолчанию. И если вы хотите, чтобы рекуррентный слой выводил последовательность, то должны указать параметр return_sequences=True при создании слоя. Обязательно нужно это делать, когда последовательно соединяются два рекуррентных слоя.

5(w3)-video4: Outputting a sequence (18.MLg_4c)

So consider this RNN, these has two recurrent layers, and the first has return_sequences=True set up. It will output a sequence which is fed to the next layer. The next layer does not have return_sequence that's set to True, so it will only output to the final step. But notice the input_shape, it's set to None and 1. TensorFlow assumes that the first dimension is the batch size, and that it can have any size at all, so you don't need to define it. Then the next dimension is the number of timestamps, which we can set to none, which means that the RNN can handle sequences of any length. The last dimension is just one because we're using a univariate time series. If we set return_sequences to true and all recurrent layers, then they will all output sequences and the dense layer will get a sequence as its inputs. Keras handles this by using the same dense layer independently at each time stamp. It might look like multiple ones here but it's the same one that's being reused at each time step. This gives us what is called a sequence to sequence RNN. It's fed a batch of sequences and it returns a batch of sequences of the same length. The dimensionality may not always match. It depends on the number of units in the memory sale. So let's now return to a two-layer RNN that has the second one not return sequences. This will give us an output to a single dense.
---------------------------------------------------------------
Итак, рассмотрим данную РНС, в которой есть два рекуррентных слоя, и у первого установлено return_sequence = True. Этот слой выводит последовательность, которая подаётся на следующий слой. У следующего входа не установлено return_sequence=True, так что он выводит только последний шаг. Но обратите внимание, что размерность входа, input_shape=[None, 1]. TensorFlow предполагает, что первое измерение является размером пакета, а оно может иметь произвольный размер, так что задавать его не нужно. А следующее измерение — это число шагов, которое мы можем установить равным None, чтобы указать, что РНС может обрабатывать последовательности любой длины. Последнее измерение равно 1, потому что мы используем одновариантные временные ряды. Если мы установим return_sequence=True для всех рекуррентных слоев, то все они будут выдавать последовательности, и полносвязный слой получит на вход последовательность. Keras это делает, используя один и тот же полносвязный слой независимо на каждом шаге. На диаграмме это может выглядеть как множество полносвязных слоёв, но это один и тот же слой, повторно используемый на каждом шаге. Тем самым, мы получаем РНС "многие ко многим" (sequence-to-sequence). Ей на вход подаётся пакет последовательностей, и она возвращает пакет последовательностей той же длины. Размерность [входа и выхода] не всегда совпадает. Она зависит от количества нейронов в ячейке памяти. Давайте теперь вернёмся к двухслойной РНС, у которой второй слой возвращает только одно значение. Такая сеть даст только один выход на полносвязный слой.

6(w3)-video5: Lambda layers (18.MLg_4c)

But I'd like to add a couple of new layers to this, layers that use the Lambda type. This type of layer is one that allows us to perform arbitrary operations to effectively expand the functionality of TensorFlow's Keras, and we can do this within the model definition itself. So the first Lambda layer will be used to help us with our dimensionality. If you recall when we wrote the window dataset helper function, it returned two-dimensional batches of Windows on the data, with the first being the batch size and the second the number of timestamps. But an RNN expects three-dimensions; batch size, the number of timestamps, and the series dimensionality. With the Lambda layer, we can fix this without rewriting our Window dataset helper function. Using the Lambda, we just expand the array by one dimension. By setting input shape to none, we're saying that the model can take sequences of any length. Similarly, if we scale up the outputs by 100, we can help training. The default activation function in the RNN layers is tan H which is the hyperbolic tangent activation. This outputs values between negative one and one. Since the time series values are in that order usually in the 10s like 40s, 50s, 60s, and 70s, then scaling up the outputs to the same ballpark can help us with learning. We can do that in a Lambda layer too, we just simply multiply that by a 100. So let's now take a look at what it takes to build out the full RNN so we can start doing some predictions with it. You'll see that in the next video.
---------------------------------------------------------------
Я хотел бы добавить к этой сети пару новых слоёв. Лямбда-слоёв. Этот тип слоя позволяет нам выполнять произвольные операции, тем самым расширяя функциональность Keras в TensorFlow. Эти операции можно задать прямо в определении модели. Первый лямбда-слой поможет нам с размерностью данных. Если помните, мы писали вспомогательную функцию window_dataset, и она возвращала двумерный пакет оконных данных, где первым измерением был размер пакета, а вторым — число отсчётов времени. Но RNN на вход нужны трёхмерные данные: размер пакета, число отсчётов и размерность ряда. При помощи лямбда-слоя можно это исправить, не переписывая нашу вспомогательную функцию. С помощью лямбды мы просто расширим массив на одно измерение. Установив input_shape=None, мы даём понять, что модель может принимать последовательности любой длины. Аналогичным образом, умножив выходной сигнал в 100 раз, мы можем помочь в обучении. Функция активации по умолчанию в рекуррентном слое — tanh, гиперболический тангенс. Его значения лежат в диапазоне от -1 до 1. Поскольку значения временного ряда обычно на порядок больше, составляя десятки: 40-50-60-70, — то пропорциональное увеличение выходных значений до сопоставимых масштабов поможет нам при обучении. Мы можем и это сделать с помощью лямбда-слоя, просто умножая значение на 100. А теперь давайте посмотрим, как построить РНС целиком, чтобы можно было начать прогнозировать с её помощью. Вы увидите это в следующем видео.

7(w3)-video6: Adjusting the learning rate dynamically (18.MLg_4c)

In the previous video, you got a look at RNNs and how they can be used for sequence to vector to sequence to sequence prediction. Let's now take a look at coding them for the problem at hand and seeing if we can get good predictions in our time series using them. One thing you'll see in the rest of the lessons going forward is that I'd like to write a little bit of code to optimize the neural network for the learning rate of the optimizer. Can be pretty quick to train and we can from there save a lot of time in our hyper-parameter tuning. So here's the code for training the RNN with two layers each with 40 cells. To tune the learning rate, we'll set up a callback, which you can see here. Every epoch this just changes the learning rate a little and you can see that setup here while training. I've also introduced a new loss function to use called Huber which you can see here. The Huber function is a loss function that's less sensitive to outliers and as this data can get a little bit noisy, it's worth giving it a shot. If I run this for 100 epochs and measure the loss at each epoch, I will see that my optimum learning rate for stochastic gradient descent is between about 10 to the minus 5 and 10 to the minus 6. So now, I'll set my models compiled with that learning rate and the stochastic gradient descent optimizer. After training for 500 epochs, I will get this chart, with an MAE on the validation set of about 6.35. It's not bad, but I wonder if we can do better. So here's the loss and the MAE during training with the chart on the right is zoomed into the last few epochs. As you can see, the trend was genuinely downward until a little after 400 epochs, when it started getting unstable. Given this, it's probably worth only training for about 400 epochs. When I do that, I get these results. That's pretty much the same with the MAE only a tiny little bit higher, but we've saved 100 epochs worth of training to get it. So it's worth it. A quick look at the training MAE and loss gives us this results. So we've done quite well, and that was just using a simple RNN. Let's see how we can improve this with LSTMs and you'll see that in the next video.
---------------------------------------------------------------
В предыдущем видео вы посмотрели на РНС и на то, как использовать их для предсказаний типа "многие к одному" и "многие ко многим". Давайте теперь посмотрим, как писать код для решения таких задач, и посмотрим, удастся ли с их помощью получить хорошие прогнозы для нашего временного ряда. В следующих наших уроках я стану писать чуть больше кода для оптимизации нейросети с помощью изменения темпа обучения. Это может сильно ускорить обучение, и мы тем самым сможем сэкономить много времени на настройке гиперпараметров. Итак, вот код для обучения РНС с двумя слоями, по 40 нейронов в каждом. Чтобы настроить темп обучения, мы зададим обратный вызов, который вы видите здесь. Он на каждой эпохе немного меняет скорость обучения, так что её шаг меняется от 1e-8 до 1e-6. И вот как он задаётся при запуске обучения. Я также использую новую функцию потерь, которая называется функция Хьюбера, и вы её видите здесь. Функция Хьюбера — это функция потерь, менее чувствительная к выбросам, а поскольку наши данные могут быть шумными, то стоит её попробовать. Если я запущу обучение на протяжении 100 эпох, и измерю значение функции потерь после каждой эпохи, то увижу, что оптимальная скорость обучения для стохастического градиентного спуска находится между 1e-5 и 1e-6. Так что я задам её значение как 5e-5. Теперь я скомпилирую мою модель с этой скоростью обучения и стохастическим градиентным спуском в качестве оптимизатора. После обучения в течение 500 эпох я получу этот график, со средней ошибкой на валидационных данных около 6.35. Не так уж плохо, но мне интересно, можно ли добиться большего успеха. Вот значение функции потерь и MAE в процессе обучения, где масштаб графика справа увеличен, и на нём показаны последние несколько эпох. Как видите, была отчётливая тенденция к снижению потерь почти до 400-й эпохи, когда значение стало нестабильным. Учитывая это, вероятно, стоит обучаться только 400 эпох. Когда я так и сделаю, то получу вот такие результаты. Они почти такие же, и абсолютная ошибка лишь немногим выше, но мы сэкономили 100 эпох обучения, чтобы получить такой результат. Оно того стоило. Беглый взгляд на абсолютную ошибку и потери на тренировочном наборе даёт такие результаты. Итак, мы получили неплохой результат, и это была всего лишь простая РНС. Давайте посмотрим, насколько результат улучшится при использовании LSTM. Увидим это в следующем видео.

8(w3)-More info on Huber loss: (18.MLg_4c)

Please find the Wikipedia page here.
https://en.wikipedia.org/wiki/Huber_loss
---------------------------------------------------------------

9(w3)-video7: LSTM (18.MLg_4c)

In the previous videos, you experimented with using RNNs to predict values in your sequence. The results were good but they did need a bit of improvement as you were hitting strange plateaus in your predictions. You experimented with using different hyperparameters and you saw some improvement, but perhaps a better approach would be to use LSTMs instead of RNNs to see the impact. We'll explore that in this video. If you remember when you looked at RNNs, they looked a little bit like this. They had cells that took batches as inputs or X, and they calculated a Y output as well as the state vector, that fed into the cell along with the next X which then resulted in the Y, and the state vector and so on. The impact of this is that while state is a factor in subsequent calculations, its impacts can diminish greatly over timestamps. LSTMs add the cell state to this that keep a state throughout the life of the training so that the state is passed from cell to cell, timestamp to timestamp, and it can be better maintained. This means that the data from earlier in the window can have a greater impact on the overall projection than in the case of RNNs. The state can also be bidirectional so that state moves forwards and backwards. In the case of texts, this was really powerful. Within the prediction of numeric sequences, it may or may not be, and it'll be interesting to experiment with. I'm not going to go into a lot of detail here but hundreds videos around LSTM are terrific. From there, you can really understand how they work under the hood.
---------------------------------------------------------------
В предыдущих видео вы экспериментировали с РНС, чтобы предсказать значения в последовательности. Результаты получались хорошие, но нуждались в некотором улучшении, потому что в прогнозах возникали странные плато. Вы экспериментировали с использованием разных гиперпараметров, и наблюдали некоторое улучшение, но, возможно, лучше будет использовать LSTM вместо РНС, чтобы посмотреть, что это даст. Это мы и рассмотрим в данном видео. Если вы помните, на вид РНС выглядели примерно так. У них были ячейки, которые принимали пакеты в качестве входных данных, X, и вычисляли выход Y, а также вектор состояния, который подаётся на вход ячейке вместе со следующим X, снова давая на выходе Y и вектор состояния, и так далее. В результате, хотя вектор состояния и влияет на последующие вычисления, но его влияние может сильно уменьшаться с ходом времени. В LSTM для этого есть вектор состояний, который может хранить состояние в течение всего времени обучения, так что состояние передаётся от ячейки к ячейке, от одного момента времени к другому, и оно лучше сохраняется. Это означает, что данные из более ранних значений в пределах окна могут сильнее влиять на все последующие вычисления, чем было в случае РНС. Кроме того, вектор состояний может быть двунаправленным, так что состояние передаётся и вперёд, и назад. В случае текстов, это было очень эффективно. Но в прогнозировании числовых последовательностей это может как давать эффект, так и не давать, и будет интересно с этим поэкспериментировать. Я не буду вдаваться тут в детали, но есть сотни потрясающих видео про LSTM. По ним вы можете полностью разобраться, как LSTM устроены.

10(w3)-video8: Long Short Term Memory (LSTM) (18.MLg_4c)

Please find the link to the LSTM lesson here
https://www.coursera.org/lecture/nlp-sequence-models/long-short-term-memory-lstm-Kxoay
In the last video, you learn about the GRU, the Gated Recurring Unit and how that can allow you to learn very long range connections in a sequence. The other type of unit that allows you to do this very well is the LSTM or the long short term memory units. And this is even more powerful than the GRU, let's take a look. Here the equations from the previous video for the GRU and for the GRU we had a t = c t and two gates the update gate and the relevance gate. c(tilde) t, which is a candidate for replacing the memory cell. And then we use the gate, the update gate gamma Wu to decide whether or not to update c t using c(tilde) t. The LSTM is an even slightly more powerful and more general version of the GRU and it's due to set hook writer and Jurgen Schmidt Huber. And this was a really seminal paper, there's a huge impact on sequence modeling, although I think this paper is one of the more difficult ones to read. It goes quite a lot into the theory of vanishing gradients. And so I think more people have learned about the details of LSTM through maybe other places than from this particular paper, even though I think this paper has had a wonderful impact on the deep learning community. But these are the equations that govern the LSTM, so the will continue to the memory cell c and the candidate value for updating it c(tilde) t will be this. And so notice that for the LSTM, we will no longer have the case that a t is equal to c t. So this is what we use and so this is like the equation on the left except that with now more use a t there or a t-1, c t-1 and we are not using this gamma r this relevance. Although you can have a deviation of the LSTM and we put that back in but with a more common version of the LSTM doesn't bother with that. And then we will have an update gate same as before. So w update and I'm going to use a t-1 here, ct +bu and one new property of the LSTM is instead of having one update gate control both of these terms, we're going to have two separate terms. So instead of gamma u and 1- gamma u were going to have gamma u here and for gate k we should call gamma f. So this gate gamma f is going to be sigmoid of, pretty much what you'd expect. c t plus bf, and then we're going to have a new output gate which is sigmoid of Wo and then again, pretty much what you'd expect plus bo. And then the update value to the memory cell will be c t equals gamma u then this asterisk in those element wise multiplication. There's a vector vector, element wise multiplication plus and instead of one minus gamma u were going to have a separate for gate gamma f times c t-1. So this gives the memory cell the option of keeping the old value c t-1 and then just adding to it this new value c(tilde) t. So use a separate update and forget gates right? So this stands on update. Forget and output gates and then finally instead of 80 equals c t. Is a t equal to the output gate element wise multiply with c t. So these are the equations that govern the LSTM. And you can tell it has three gates instead of two. So it's a bit more complicated and places against in slightly different places. So here again are the equations governing the behavior of the LSTM. Once again it's traditional to explain these things using pictures, so let me draw one here. And if these pictures are too complicated don't worry about it, I probably find the equations easier to understand than the picture but just show the picture here for the intuitions it conveys. The particular picture here was very much inspired by a blog post due to Chris Kohler titled Understanding LSTM networks. And the diagram drawn here is quite similar to one that he drew in his blog post. But the key things to take away from this picture or maybe that you use a t-1 and x t to compute all the gate values. So in this picture you have a t-1 and x t coming together to compute a forget gate to compute the update gates and the computer the output gate. And they also go through a tarnish to compute a c(tilde) t. And then these values are combined in these complicated ways with element wise multiplies and so on to get a c t from the previous c t -1. Now one element of this is interesting is if you hook up a bunch of these in parallel so that's one of them and you connect them, connect these temporarily. So there's the input x 1, then x 2, x 3. So you can take these units and just hook them up as follows where the output a for a period of time, 70 input at the next time set. And similarly for C and I've simplified the diagrams a little bit at the bottom. And one cool thing about this, you notice is that this is a line at the top that shows how so long as you said the forget and the update gates, appropriately, it is relatively easy for the LSTM to have some value C0 and have that be passed all the way to the right to have, maybe C3 equals C0. And this is why the LSTM as well as the GRU is very good at memorizing certain values. Even for a long time for certain real values stored in the memory cells even for many, many times steps. So that's it for the LSTM, as you can imagine, there are also a few variations on this that people use. Perhaps the most common one, is that instead of just having the gate values be dependent only on a t-1, xt. Sometimes people also sneak in there the value c t -1 as well. This is called a peephole connection. Not a great name maybe, but if you see peephole connection, what that means is that the gate values may depend not just on a t-1 but and on x t but also on the previous memory cell value. And the peephole connection can go into all three of these gates computations. So that's one common variation you see of LSTMs one technical detail is that these are say 100 dimensional vectors. If you have 100 dimensional hidden memory cell union. So is this and so say fifth element of c t-1 affects only the fifth element of the correspondent gates. So that relationship is 1 to 1 where not every element of the 100 dimensional c t-1 can affect all elements of the gates, but instead the first element of c t-1 affects the first element of the gates. Second element affects second elements and so on. But if you ever read the paper and see someone talk about the peephole connection, that's what they mean, that c t -1 is used to affect the gate value as well. So that's it for the LSTM, when should you use a GRU and when should you use an LSTM. There is a widespread consensus in this. And even though I presented GRUs first in the history of deep learning, LSTMs actually came much earlier and then GRUs were relatively recent invention that were maybe derived as partly a simplification of the more complicated LSTM model. Researchers have tried both of these models on many different problems and on different problems the different algorithms will win out. So there isn't a universally superior algorithm, which is why I want to show you both of them. But I feel like when I am using these, the advantage of the GRU is that it's a simpler model. And so it's actually easier to build a much bigger network only has two gates, so computation runs a bit faster so it scales the building, somewhat bigger models. But the LSTM is more powerful and more flexible since there's three gates instead of two. If you want to pick one to use, I think LSTM has been the historically more proven choice. So if you had to pick one, I think most people today will still use the LSTM as the default first thing to try. Although I think the last few years GRUs have been gaining a lot of momentum and I feel like more and more teams are also using GRUs because they're a bit simpler but often were, just as well and it might be easier to scale them to even bigger problems. So that's it for LSTMs with either GRUs or LSTMS, you'll be able to build new networks that can capture much longer range dependencies.
---------------------------------------------------------------
В последнем видео вы узнаете о GRU, Gated Recurring Unit и о том, как это может позволить вам изучать соединения очень дальнего действия в последовательности. Другой тип устройства, который позволяет вам делать это очень хорошо, — это LSTM или блоки долговременной кратковременной памяти. А это даже мощнее ГРУ, давайте посмотрим. Здесь уравнения из предыдущего видео для ГРУ и для ГРУ у нас были t = c t и два вентиля: вентиль обновления и вентиль релевантности. c(тильда) t, который является кандидатом на замену ячейки памяти. И затем мы используем ворота, ворота обновления гамма Wu, чтобы решить, обновлять ли c t с помощью c(tilde) t. LSTM — это даже немного более мощная и более общая версия GRU, созданная писателем set hook и Юргеном Шмидтом Хубером. И это была действительно основополагающая статья, она оказала огромное влияние на моделирование последовательностей, хотя я думаю, что эта статья одна из самых сложных для чтения. Это довольно много связано с теорией исчезающих градиентов. И поэтому я думаю, что больше людей узнали о деталях LSTM, возможно, из других источников, а не из этой конкретной статьи, хотя я думаю, что эта статья оказала замечательное влияние на сообщество глубокого обучения. Но это уравнения, которые управляют LSTM, поэтому они будут продолжаться до ячейки памяти c, а значение кандидата для ее обновления c (тильда) t будет таким. Итак, обратите внимание, что для LSTM у нас больше не будет случая, когда a t равно c t. Итак, это то, что мы используем, и это похоже на уравнение слева, за исключением того, что теперь больше используется t там или t-1, c t-1, и мы не используем эту гамму или эту релевантность. Хотя у вас может быть отклонение от LSTM, и мы вернем его, но с более распространенной версией LSTM это не беспокоит. И тогда у нас будут такие же ворота обновлений, как и раньше. Итак, w update, и я собираюсь использовать здесь t-1, ct +bu и одно новое свойство LSTM — вместо того, чтобы один шлюз обновления контролировал оба этих термина, у нас будет два отдельных термина. Таким образом, вместо gamma u и 1-gamma u здесь будет гамма u, а для ворот k мы должны назвать gamma f. Таким образом, эта гамма ворот f будет сигмовидной, чего и следовало ожидать. c t плюс bf, а затем у нас будет новый выходной вентиль, который является сигмоидой Wo, и опять же, почти то, что вы ожидаете, плюс bo. И тогда значение обновления в ячейке памяти будет равно ct равно gamma u, а затем этой звездочке в этих поэлементных умножениях. Есть векторный вектор, поэлементное умножение плюс и вместо одного минус гамма u будет иметь отдельную для ворот гамму f раз c t-1. Таким образом, это дает ячейке памяти возможность сохранить старое значение c t-1, а затем просто добавить к нему это новое значение c(тильда) t. Так что используйте отдельное обновление и забудьте о гейтах, верно? Так что это стоит на обновлении. Забудьте и выведите гейты и тогда, наконец, вместо 80 будет равно c t. Является ли a t равным элементу выходного затвора, умноженным на c t. Итак, это уравнения, которые управляют LSTM. И вы можете сказать, что у него трое ворот вместо двух. Так что это немного сложнее и размещается в немного разных местах. Итак, здесь снова приведены уравнения, управляющие поведением LSTM. Опять же, традиционно объяснять эти вещи с помощью картинок, так что позвольте мне нарисовать одну здесь. И если эти изображения слишком сложны, не беспокойтесь об этом, я, вероятно, нахожу уравнения более понятными, чем изображение, но просто покажите изображение здесь для интуитивного понимания, которое оно передает. Конкретное изображение здесь было очень вдохновлено сообщением в блоге Криса Колера под названием «Понимание сетей LSTM». И схема, нарисованная здесь, очень похожа на ту, которую он нарисовал в своем блоге. Но ключевые вещи, которые можно извлечь из этой картины, или, может быть, то, что вы используете t-1 и x t для вычисления всех значений вентиля. Итак, на этом рисунке у вас есть t-1 и x t, которые объединяются для вычисления вентиля забывания для вычисления вентиля обновления, а компьютер — выходного вентиля. И они также проходят через потускнение, чтобы вычислить c (тильду) t. А затем эти значения комбинируются сложными способами с поэлементным умножением и так далее, чтобы получить значение c t из предыдущего c t -1. Теперь интересен один элемент: если вы соедините их несколько параллельно, так что это один из них, и вы соедините их, соедините их временно. Итак, есть вход x 1, затем x 2, x 3. Итак, вы можете взять эти единицы и просто подключить их следующим образом, где выход a за определенный период времени, 70 вход в следующий раз. И аналогично для C, и я немного упростил диаграммы внизу. И одна интересная вещь в этом, как вы заметили, заключается в том, что это строка вверху, которая показывает, как долго, как вы сказали, ворота «забыть» и «обновить», соответственно, для LSTM относительно легко иметь некоторое значение C0 и иметь это пройти весь путь вправо, может быть, C3 равно C0. И именно поэтому LSTM, а также GRU очень хорошо запоминают определенные значения. Даже в течение длительного времени для некоторых реальных значений, хранящихся в ячейках памяти даже для много-много раз шагов. Вот и все, что касается LSTM, как вы можете себе представить, есть также несколько вариантов, которые люди используют. Возможно, самый распространенный из них заключается в том, что вместо того, чтобы значения вентиля зависели только от t-1, xt. Иногда туда же подсовывают и значение c t -1. Такое соединение называется глазком. Может быть, не очень удачное название, но если вы видите глазок, это означает, что значения вентилей могут зависеть не только от t-1, но и от x t, но также и от предыдущего значения ячейки памяти. И глазок может использоваться во всех трех вычислениях ворот. Итак, это одна из распространенных вариаций LSTM, которую вы видите. Одна техническая деталь заключается в том, что это, скажем, 100-мерные векторы. Если у вас есть 100-мерный союз скрытых ячеек памяти. Так вот этот и так сказать пятый элемент c t-1 влияет только на пятый элемент соответствующих вентилей. Таким образом, это отношение 1 к 1, где не каждый элемент 100-мерного c t-1 может влиять на все элементы ворот, а вместо этого первый элемент c t-1 влияет на первый элемент ворот. Второй элемент влияет на вторые элементы и так далее. Но если вы когда-нибудь прочитаете статью и увидите, что кто-то говорит о подключении через глазок, они имеют в виду, что c t -1 также используется для воздействия на значение затвора. Вот и все для LSTM, когда вы должны использовать GRU и когда вы должны использовать LSTM. В этом существует широко распространенное мнение. И хотя я представил GRU первыми в истории глубокого обучения, LSTM на самом деле появились намного раньше, а затем GRU были относительно недавним изобретением, которое, возможно, было получено как частичное упрощение более сложной модели LSTM. Исследователи опробовали обе эти модели на множестве разных задач, и в разных задачах выигрывали разные алгоритмы. Итак, не существует универсально превосходного алгоритма, поэтому я хочу показать вам оба из них. Но мне кажется, что когда я их использую, преимущество ГРУ в том, что это более простая модель. И поэтому на самом деле проще построить гораздо большую сеть, имеющую только два входа, поэтому вычисления выполняются немного быстрее, поэтому они масштабируют здание, несколько более крупные модели. Но LSTM мощнее и гибче, поскольку у него три ворот вместо двух. Если вы хотите выбрать один для использования, я думаю, что LSTM был исторически более проверенным выбором. Так что, если вам нужно было выбрать один, я думаю, что большинство людей сегодня по-прежнему будут использовать LSTM по умолчанию в первую очередь, чтобы попробовать. Хотя я думаю, что за последние несколько лет GRU набирают обороты, и я чувствую, что все больше и больше команд также используют GRU, потому что они немного проще, но часто так и было, и их может быть легче масштабировать для еще большие проблемы. Вот и все, что касается LSTM с GRU или LSTMS, вы сможете создавать новые сети, которые могут захватывать гораздо более дальние зависимости.

11(w3)-LSTM notebook (Lab 2): (18.MLg_4c)

You can use the notebook here to follow along the LSTM coding demo in the next video.
C4_W3_Lab_2_LSTM.ipynb
Ungraded Lab: Using a multi-layer LSTM for forecasting
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W3/ungraded_labs/C4_W3_Lab_2_LSTM.ipynb#scrollTo=sV_nvXSQGJPK
---------------------------------------------------------------

12(w3)-video9 Coding LSTMs (18.MLg_4c)

So let's now take a look at some code for LSTMs and how they can work with the data that we've been playing with all week. So here's the update to our code to use LSTMs. Let's unpack it and take a look at the interesting parts. First of all is the tf.keras.backend.clear_session, and this clears any internal variables. That makes it easy for us to experiment without models impacting later versions of themselves. After the Lambda layer that expands the dimensions for us I've added a single LSTM layer with 32 cells. I've also made a bidirectional to see the impact of that on a prediction. The output neuron will give us our prediction value. I'm also using a learning rate of one times 10 _ minus six and that might be worth experimenting with too. So here's the results of running this LSTM on the synthetic data that we've been using throughout the course. The plateau under the big spike is still there and are MAE is in the low sixes. It's not bad, it's not great, but it's not bad. The predictions look like there might be a little bit on the low side too. So let's edit our code to add another LSTM to see the impact. Now you can see the second layer and note that we had to set return sequences equal to true on the first one in order for this to work. We train on this and now we will see the following results. Here's the chart. Now it's tracking much better and closer to the original data. Maybe not keeping up with the sharp increase but at least it's tracking close. It also gives us a mean error that's a lot better and it's showing that we're heading in the right direction. If we edit our source to add a third LSTM layer like this, by adding the layer and having the second layer return sequences is true we can then train and run it, and we'll get the following output. So that's it for looking at LSTMs and predicting our sequences. In the next video you'll take a look at using convolutions to see what the impact will be on using them for predicting time-series content.
---------------------------------------------------------------
Теперь давайте взглянем на код для LSTM, и на то, как LSTM справится с данными, с которыми мы играем всю эту неделю. Итак, вот новая редакция нашего кода, с использованием LSTM. Давайте присмотримся поближе к интересным фрагментам. Прежде всего, это tf.keras.backend.clear_session, данный вызов очищает все внутренние переменные. Это позволяет нам экспериментировать так, чтобы модели не влияли на свои же более поздние версии. После лямбда-слоя, который увеличивает размерность данных, я добавил один слой LSTM с 32 ячейками. Я также сделал его двунаправленным, чтобы посмотреть, как это повлияет на прогнозирование. Выходной нейрон будет давать нам прогнозируемое значение. Я также использую скорость обучения, равную 1e-6, и, возможно, с ней тоже стоит поэкспериментировать. Итак, вот результаты запуска этой LSTM на тех синтетических данных, которые мы используем в течение всего курса. Плато перед резким пиком по-прежнему здесь, и ошибка чуть больше 6. Не так уж плохо, но и отличным не назовёшь. Предсказания выглядят так, словно они слегка занижаются. Давайте изменим наш код, добавив еще одну LSTM, и посмотрим, как это повлияет. Теперь вы видите второй слой, — обратите внимание, что нам пришлось задать параметр return_sequences=True для первого слое, чтобы всё работало. Обучаем эту сеть и видим следующие результаты. Вот график. Теперь сеть прогнозирует гораздо лучше и ближе к исходным данным. Возможно, не угадывая резкие всплески, но, как минимум, приближаясь к ним. Также мы получаем намного лучшую абсолютную ошибку, и это указывает, что мы движемся в верном направлении. Если изменить наш код, добавив третий слой LSTM, вот так, добавив слой и задав и для второго слоя return_sequences=True, то можно затем обучить и прогнать модель, и получить вот такой результат. Разница не особо велика, и абсолютная ошибка ухудшилась. Итак, мы попробовали предсказать нашу последовательность с помощью LSTM. В следующем видео вы увидите, как использовать свёртки, и каков будет эффект от их использования для предсказания временных рядов.

13(w3)- Week 3 Quiz: (18.MLg_4c)

1) If X is the standard notation for the input to an RNN, what are the standard notations for the outputs?:
1. Y
2. H
3. Y(hat) and H (+)
4. H(hat) and Y
2) What is a sequence to vector if an RNN has 30 cells numbered 0 to 29:
1. The Y(hat) for the second cell
2. The Y(hat) for the last cell (+)
3. The total Y(hat) for all cells
4. The average Y(hat) for all 30 cells
3) What does a Lambda layers in a neural network do?:
1. There are no Lambda layers in a neural network
2. Allows you to execute arbitrary code while training (+)
3. Changes the shape of the input or output data
4. Pauses training without a callback
4) What does the axis parameter of tf.expand_dims do? :
1. Defines the dimension index at which you will expand the shape of the tensor (+)
2. Defines if the tensor is X or Y
3. Defines the axis around which to expand the dimensions
4. Defines the dimension index to remove whine you expand the tensor
5) A new loss function was introduced in this module, name after a famous statistician. What is it called?:
1. Hubble loss
2. Huber loss (+)
3. Hawking loss
4. Hyatt loss
6) What's the primary difference between a simple RNN and an LSTM?:
1. In addition to the H output, LSTMs have a cell state that runs across all cells (+)
2. LSTMs have a single output, RNNs have multiple
3. In addition to the H output, Rnns have a cell state that runs across all cells
4. LSTMs have multiple outputs, RNNs have a single one
7) If you want to clear out all temporary variables that tensorflow might have from previous sessions, what code do you run?:
1. tf.cache.backend, clear_session()
2. tf.keras.clear_session (-)
3. tf.chache.clear_session()
4. tf.keras.backen.clear_session() (+)
8) What happens if you define a neural network with these two layers?:
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32))
tf.keras.layers.Dense(1)
1. Your model will compile and run correctly (-)
2. Your model will fail because you need return_sequences=True after each LSTM layer
3. Your model will fail because you need return_sequences=True after the first LSTM layer (+)
4. Your model will fail because you have the same number of cells in each LSTM

14(w3)- Week 3 Wrap up: (18.MLg_4c)

Now that you've built on your DNNs with RNNs and LSTMs, it's time to put it all together using CNNs and some real world data.
Next week you'll do that, exploring the prediction of sunspot data from a couple of hundred years worth of measurements!
---------------------------------------------------------------
Теперь, когда вы построили свои DNN с помощью RNN и LSTM, пришло время собрать все это вместе, используя CNN и некоторые данные из реального мира.
На следующей неделе вы сделаете это, исследуя предсказание данных о солнечных пятнах на основе измерений за пару сотен лет!

15(w3)- Lecture Notes Week 3: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
These slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode

16(w3)- Programming Assignment: Forecast using RNNs or LSTMs: (18.MLg_4c)

Week 3: Using RNNs to predict time series
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/programming/30QuE/forecast-using-rnns-or-lstms/lab?path=%2Fnotebooks%2FC4W3_Assignment.ipynb

NEXT week_4 (18.MLg_4c)

/+++++++++++++++++++++++++++++++++++++++++++++++++++++++/

(w4)Real-world time series data (18.MLg_4c)

(Реальные данные временных рядов)
(Sequences, Time Series and Prediction)
---------------------------------------------------------------
Video: 22 minutes
Self-study: 2h 38 min
Graded tasks (Tasks to be assessed): 2

(w4) Content (18.MLg_4c)

1. 2. 3. 4.

(w4) Introduction: (18.MLg_4c)

On top of DNNs and RNNs, let's also add convolutions, and then put it all together using a real-world data series -- one which measures sunspot activity over hundreds of years, and see if we can predict using it.
---------------------------------------------------------------
Вдобавок к DNN и RNN давайте также добавим свертки, а затем соберем все вместе, используя ряды реальных данных, которые измеряют активность солнечных пятен за сотни лет, и посмотрим, сможем ли мы предсказать их использование.

1(w4)-video1: Week 4 - A conversation with Andrew Ng (18.MLg_4c)

Welcome to the final week of this final course of this specialization. There's a lot happening this week that I hope you find fun and exciting. You get to take sunspot data, the real data and apply a 1D convnet to that. So this is generalization of the 2D curve you see, and on top of that and LSTM and on top of that a dense neural networks. So a lot of pieces you've learned will come together to help you build an effective sunspot prediction. This specialization was called Tensor Flow in practice. So one of the things that Andrew and I have been really excited about is helping you to be able to put everything that you've been learning in this specialization into practice. So in this course we've been using synthetic data for the last three weeks, but we're now taking you away from the synthetic data and giving you the real-world sunspot data that Andrew mentioned; convolutional neural networks and 1D cams, LSTMs, deep neural networks, we'll be able to mash them all together and hopefully come up with some nice prediction engines for sunspot activity. So by the end of this week, you have built a pretty sophisticated neural network model that it puts together many of these pieces. By doing that, I hope you may be able to start seeing how you could maybe assemble these pieces you've learned in Tensor Flow to build other rich neural networks as well. So please go on to the next video.
---------------------------------------------------------------
Добро пожаловать на последнюю неделю завершающего курса этой специализации. На этой неделе будет масса всего, и я надеюсь, что вам будет интересно. Вы возьмёте данные о пятнах на Солнце, реальные данные, — и примените к ним одномерные свёртки. Тем самым, мы обобщим двумерные свёртки, и поверх них будет идти LSTM, а поверх неё — полносвязная нейросеть. Множество изученных вами частей будет сведено воедино, чтобы вы могли эффективно прогнозировать солнечную активность. Эта специализация называется "TensorFlow на практике". Так что мы с Эндрю очень рады возможности помочь вам собрать воедино всё то, что вы изучали на протяжении всей этой специализации, и применить это на практике. В течение предыдущих трёх недель этого курса мы использовали синтетические данные, но теперь мы расстаёмся с синтетическими данными и даём вам реальные данные по солнечной активности, о которых сказал Эндрю. Свёрточные нейросети, LSTM, глубокие нейросети — мы хорошенько всё это замесим и будем надеяться, что выйдет хороший инструмент для прогнозирования солнечной активности. Итак, к концу этой недели у вас будет готова довольно сложная модель на основе нейросетей, которая сведёт воедино многие из перечисленных частей. Я надеюсь, что разрабатывая её, вы начнёте понимать, как собирать все эти части TensorFlow, которые вы изучили, чтобы строить и другие сложные нейросети. Приглашаем вас перейти к следующему видео.

2(w4)-video2: Convolutions (18.MLg_4c)

Last week, we looked at recurrent neural networks including a simple RNN and an LSTM. You saw how they could be useful in learning a sequence like the one that we've been looking at. And how the LSTMs removed some of the issues we had with an RNN. This week, you'll go one step further, combining convolutions with LSTMs to get a very nicely fitting model. We'll then apply that to real world data instead of this synthetic data set that we've been working on since the beginning of this course. Here's the LSTM that you looked at last week, except that I've added something at the beginning of the sequential stack. It's a Conv1D where we'll try to learn 32 filters. It's a one dimensional convolution. So we'll take a five number window and multiply out the values in that window by the filter values, in much the same way as image convolutions are done. Check back to the convolutions course to learn more about that.
---------------------------------------------------------------
На прошлой неделе мы рассмотрели рекуррентные нейросети, включая простую РНС и LSTM. Вы видели, насколько они полезны при обучении на последовательностях, вроде той, которая у нас была. И видели, как LSTM устраняют некоторые из проблем, возникавших с РНС. На этой неделе вы пойдёте еще дальше, объединяя свёртки с LSTM и получая в результате модель, весьма близкую к данным. Затем мы применим её к реальным данным вместо синтетических, над которыми мы работали с начала данного курса. Вот та LSTM, рассмотренная на прошлой неделе, только я добавил ещё кое-что в самом начале цепочки слоёв. Это слой Conv1D, в котором мы будем обучать 32-м фильтра. Это одномерная свёртка. Мы возьмём окно из пяти чисел и умножим значения в окне на значения фильтра, практически так же, как мы делали со свёртками на изображениях. Обратитесь к курсу по свёрточным сетям, чтобы больше узнать об этом.

3(w4)-Convolutional neural networks course: (18.MLg_4c)

More information on CNNs can be found on Andrews course within the Deep Learning Specialization.
If you are curious about the content and would like to learn more, here is the link to the course.
https://www.coursera.org/learn/convolutional-neural-networks
---------------------------------------------------------------

4(w4)-video3: Bi-directional LSTMs (18.MLg_4c)

One important note is that while we got rid of the Lambda layer that reshaped the input for us to work with the LSTM's. So we're actually specifying an input shape on the curve 1D here. This requires the windowed dataset helper function that we've been working with all along. Also similar to last week, the code will attempt lots of different learning rates changing them epoch by epoch and plotting the results. With this data and the convolutional and LSTM-based network, we'll get a plot like this. It clearly bottoms are around 10 to the minus five after which it looks a bit unstable, so we'll take that to be our desired learning rates. Thus when we define the optimizer will set the learning rate to be 1e-5 as shown here. When we train for 500 epochs we'll get this curve. It's a huge improvement over earlier. The peak has lost its plateau but it's still not quite right, it's not getting high enough relative to the data. Now of course noise is a factor and we can see crazy fluctuations in the peak caused by the noise, but I think our model could possibly do a bit better than this. Our MAE is below five, but I would bet that outside of that first peak is probably a lot lower than that. One solution might be to train a little bit longer. Even though our MAE loss curves look flat at 500 epochs, we can see when we zoom in that they're slowly diminishing. The network is still learning albeit slowly. Now one method would be to make your LSTMs bidirectional like this. When training, this looks really good giving very low loss in MAE values sometimes even less than one. But unfortunately it's overfittingng when we plot the predictions against the validation set, we don't see much improvement and in fact, you might need to tweak some of the parameters to avoid overfitting. Some of the problems are clearly visualize when we plot the loss against the MAE, there's a lot of noise and instability in there. One common cause for small spikes like that is a small batch size introducing further random noise. I won't go into the details here, but if you check out Andrew's videos and his course on optimizing for gradient descent, there's some really great stuff in there. One hint was to explore the batch size and to make sure it's appropriate for my data. So in this case it's worth experimenting with different batch sizes. So for example experimented with different batch sizes both larger and smaller than the original 32, and when I tried 16 you can see the impact here on the validation set, and here on the training loss and MAE data. Okay so by combining CNNs and LSTMs we've been able to build our best model yet, despite some rough edges that could be refined. In the next video, we'll step through a notebook that trains with this model so that you can see it for yourself, and also we'll maybe learn how to do some fine-tuning to improve the model even further. After that, we'll take the model architecture and apply it to some real-world data instead of the synthetic ones that you've been using all along.
---------------------------------------------------------------
Обратите внимание: мы избавились от лямбда-слоя, менявшего размерность входа для работы с LSTM. Поэтому теперь мы определяем размерность входа в слой Conv1D вот здесь. Для этого нужно изменить вспомогательную функцию windowed_datasetet, с которой мы работали всё это время. Мы просто будем использовать в ней tf.expand_dims, чтобы увеличить размерность ряда (на 1) перед тем, как работать с ним дальше. Как и на прошлой неделе, в код мы будем пробовать множество различных темпов обучения, изменяя их от эпохи к эпохе и выводя на график результаты. На этих данных для нейросети со свёртками и LSTM у нас получится график вроде этого. В нём отчётливый минимум в районе 1e-5, после которого результат выглядит несколько нестабильным, так что мы возьмём это число в качестве нужного темпа обучения. Таким образом, во время инициализации оптимизатора мы зададим темп обучения, равный 1e-5, как показано здесь. После обучения в течение 500 эпох мы получим такую кривую. Это огромный прогресс по сравнению с тем, что было раньше. Пик [слева] перестал быть похожим на плато, но прогноз всё ещё недостаточно точен, он всё ещё недостаточно тесно следует за данными. Конечно, шум — это важный фактор, и мы видим сумасшедшие флуктуации, вызванные шумом, в окрестностях максимума, но я думаю, наша модель, возможно, могла бы работать получше, чем сейчас. Наша абсолютная ошибка меньше 5, но готов побиться об заклад, что вне окрестностей первого пика она намного ниже. Одним из решений могло бы быть более продолжительное обучение. Хотя функция потерь и выглядит плоской в течение 500 эпох, но если увеличить график, мы видим, что она понемногу уменьшается. Сеть всё ещё учится, но медленно. Ещё один возможный способ — сделать LSTM-слои двунаправленными, как здесь. При обучении прогресс выглядит очень хорошо, давая очень низкую абсолютную ошибку — иногда даже меньше 1. Но, к сожалению, модель переобучается, и когда мы получаем прогнозы на валидационных данных, то не видим улучшения — более того, абсолютная ошибка даже ухудшилась. Тем не менее, это шаг в верном направлении, и со временем мы рассмотрим подобную архитектуру, но, возможно, потребуется подстроить некоторые параметры, чтобы избежать переобучения. Некоторые проблемы явно видны, когда мы строим график абсолютной ошибки и функции потерь: картина неустойчивая, с большим количеством шума. Одна из распространенных причин появления подобных небольших пиков — это маленький размер пакета, который дополнительно вносит случайный шум. Я не буду здесь вдаваться в подробности, но если вы посмотрите видео Эндрю из его курса по оптимизации градиентного спуска, то там есть очень полезные вещи. И один из советов — проверить размер пакета и убедиться, что он соответствует данным. Так что, стоит поэкспериментировать с разными размерами пакета. Например, проверить разные размеры пакета, как больше, так и меньше, чем исходные 32, — и когда я взял размер 16, то посмотрите, какой эффект это произвело на предсказания на валидационных данных. А вот какими стали функция потерь и абсолютная ошибка на обучающей выборке. Итак, объединяя свёрточные сети и LSTM, мы смогли построить нашу лучшую на данный момент модель, несмотря на некоторые шероховатости, которые можно отполировать. В следующем видео мы пройдёмся пошагово по блокноту, в котором обучается эта модель, чтобы вы могли увидеть всё своими глазами, и, возможно, мы также узнаем, как подстраивать параметры, ещё более улучшая модель. После этого мы возьмём архитектуру этой модели, и применим её к реальным данным вместо синтетических, которыми пользовались весь этот курс.

5(w4)-vide4: More on batch sizing (18.MLg_4c)

Please find more information here
https://www.youtube.com/watch?v=4qJaSmvhxi8
---------------------------------------------------------------

6(w4)-Convolutions with LSTM notebook (Lab 1): (18.MLg_4c)

The next video is a screencast demonstrating how to use convolution layers with the LSTM network you built last week. You can find the link to the notebook here.
C4_W4_Lab_1_LSTM.ipynb
Ungraded Lab: Using Convolutions with LSTMs
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W4/ungraded_labs/C4_W4_Lab_1_LSTM.ipynb#scrollTo=GYEYC1orNFdN
---------------------------------------------------------------

7(w4)-vide5: Convolutions with LSTM (18.MLg_4c)

In the previous video, you saw how you could stack a convolutional layer with LSTMs and bidirectional LSTMs to do sequence prediction. In this video, we'll go through a workbook for this, which you can then try for yourself later. This code will generate the synthetic time series for you, and this code will turn the array of data into a dataset for training. Note that we've expanded the dimensions on the first line. This first copy of the neural network has run for a quick 100 Epoch run to try and pick the optimum learning rate for the optimizer. When it's done, we'll plot the results and we'll see the optimum value, so we'll set that on the SGD for the next training run. We'll train for 500 Epochs now and keep an eye on our loss and our mae. When it's done, we'll run our forecast and plot the results. Already the curve is looking much better and the plateau that we'd seen in previous training has vanished, and our mae is low, it's just above five at the validation set. Finally, if we plot our training loss and mae, we also see a healthy curve downwards.
---------------------------------------------------------------
В предыдущих видео вы видели, как сочетать свёрточный слой с LSTM или двунаправленным LSTM для прогнозирования значений ряда. В этом видео мы пройдёмся по подготовленному для этого пособию, а затем вы сможете поработать с ним самостоятельно. Как всегда, давайте проверим, установлен ли у вас TensorFlow 2. Если нет, установите самую свежую ночную сборку или последний релиз с tenorflow.org. Когда вы убедитесь, что у вас версия 2, этот код сгенерирует вам синтетический временной ряд, а вот этот код преобразует массив данных в набор для обучения. Обратите внимание, что в первой строке мы увеличиваем размерность данных. Эта вспомогательная функция вычислит нам прогноз после обучения. Первый экземпляр нейросети обучается недолгие 100 эпох, чтобы проверить и задать в оптимизаторе оптимальный темп обучения. Когда она закончит работу, мы выведем график с результатами и увидим, что 1e-5 — оптимальное значение, так что мы передадим его в стохастический градиентный спуск на следующем прогоне. В этот раз мы будем обучаться 500 эпох и следить за функцией потерь и абсолютной ошибкой. Когда обучение закончится, мы посчитаем наши прогнозы и построим график с результатами. Кривая уже выглядит намного лучше, и плато, которое мы видели на предыдущих моделях, исчезло. Абсолютная ошибка тоже низкая, она лишь немногим выше 5 на валидационных данных. Наконец, если мы построим график функции потерь и абсолютной ошибки, то увидим хорошие нисходящие кривые.

8(w4)-vide6: Real data - sunspots (18.MLg_4c)

Over the last few weeks, you looked at time-series data and examined a few techniques for forecasting that data including statistical analysis, linear regression, and machine-learning with both deep learning networks and recurrent neural networks. But now we're going to move beyond the synthetic data to some real-world data and apply what we've learned to creating forecasts for it. Let's start with this dataset from Kaggle, which tracks sunspots on a monthly basis from 1749 until 2018. Sunspots do have seasonal cycles approximately every 11 years. So let's try this out to see if we can predict from it. It's a CSV dataset with the first column being an index, the second being a date in the format year, month, day, and the third being the date of that month that the measurement was taken. It's an average monthly amount that should be at the end of that month. You can download it from Kaggle or if you're using the notebook in this lesson, I've conveniently hosted it for your on my Cloud Storage. It's a pretty simple dataset, but it does help us understand a little bit more about how to optimize our code to predict the dataset based on the nature of its underlying data. Of course, one size does not fit all particularly when it comes to data that has seasonality. So let's take a look at the code. Okay, first of all, if you're using a codelab, then you'll need to get the data into your codelab instance. This code will download the file that I've stored for you. You should really get it from Kaggle and store it on your own server or even manually upload it to codelab, but for convenience, I've stored it here. Here's the code to read the CSV file and get its data into a list of sunspots and timestamps. We'll start by importing the CSV library. Then we'll open the file. If you're using the codelab and the W get code that you saw earlier, downloads the CSV and puts it into slash temp. So this code just reads it out of there. This line, next reader, is called Before we loop through the rows and the reader, and it's simply reads the first line and we end up throwing it away. That's because the column titles are in the first line of the file as you can see here. Then, we will look through the reader reading the file line by line. Our sunspots are actually in column 2 and we want them to be converted into a float. As the file is read, every item will be read as a string so we may as well convert them now instead of iterating through the list later and then converting all the datatypes. Similarly, we'll read the time steps as integers. As much of the code we'll be using to process these deals with NumPy arrays, we may as well now convert a list to NumPy arrays. It's more efficient to do it this way, build-up your data in a throwaway list and then convert it to NumPy than I would have been to start with NumPy arrays, because every time you append an item to a NumPy, there's a lot of memory management going on to clone the list, maybe a lot of data that can get slow. If we plot our data it looks like this. Note that we have seasonality, but it's not very regular with some peaks and much higher than others. We also have quite a bit of noise, but there's no general trend. As before, let's split our series into a training and validation datasets. We'll split at time 1,000. We'll have a window size of 20, batch size of 32, and a shuffled buffer of 1,000. We'll use the same window dataset code that we've been using all week to turn a series into a dataset which we can train on.
---------------------------------------------------------------
За последние несколько недель вы работали с временными рядами и исследовали несколько методов для предсказывания их значений, включая статистический анализ, линейную регрессию и машинное обучение, включая как глубокие нейросети, так и рекуррентные нейронные сети. Но сейчас мы выйдем за пределы синтетических данных, воспользуемся настоящими данными из окружающего мира и применим то, что мы выучили, чтобы предсказать их. Давайте начнём с этого набора данных с Kaggle, где даётся ежемесячная сводка по числу пятен на Солнце, с 1749 по 2018 год. Солнечные пятна обладают цикличностью с периодом около 11 лет. Давайте посмотрим, что мы сможем для них предсказать. Этот набор данных находится в CSV-файле, где первая колонка — индекс, вторая — дата в формате год-месяц-день, а третья — данные за месяц, когда были проведены измерения. Это среднее число пятен, которое получилось к концу месяца. Вы можете скачать набор с Kaggle но если вы используете блокнот этого урока, то для вашего удобства я разместил набор в своём облачном хранилище. Это довольно простой набор данных, но он поможет нам немного лучше разобраться в том, как оптимизировать наш код, чтобы предсказывать значения ряда, основываясь на природе данных, которые он описывает. Конечно, не существует универсального подхода, особенно, когда дело доходит до данных с циклической компонентой. Итак, давайте посмотрим на код. Итак, во-первых, если вы используете colab, вам нужно будет затянуть данные в ваш colab. Этот код скачает файл, который я разместил для вас. По хорошему, вам нужно было бы скачать его с Kaggle и сохранить на своём сервере, или хотя бы загрузить вручную в colab, но для удобства я сохранил его тут. Этот код читает CSV-файл и загружает данные в списки для числа пятен и временных меток. Сперва импортируем библиотеку csv. Затем откроем файл. Если вы используете colab, то вызов wget, который вы только что видели, скачает файл и сохранит его в /tmp. Так что этот код просто читает его оттуда. Эта строка, next(reader), выполняется перед запуском цикла по всем строкам из reader, здесь просто считывается первая строка, которую мы отбрасываем. Это потому что в первой строке, как видите, находятся имена столбцов. Затем мы проходим циклом по строкам из reader, читая файл строка за строкой. Количество пятен лежат во втором столбце, и мы хотим преобразовать этот текст к числу с плавающей запятой. По мере чтения файла каждый его элемент считывается в виде строки, и можно преобразовать её в число сразу, а не считывать весь список целиком, лишь потом преобразовывая типы данных. Аналогично, мы считываем индексы как целые числа. Поскольку большая часть кода для обработки данных будет использовать массивы NumPy, можно сразу преобразовать наши списки в эти массивы. Так будет эффективнее собирать данные в одноразовый список, а затем преобразовывать его к NumPy-массиву — а не работать сразу с массивами NumPy, т.к. при каждом добавлении элемента в NumPy-массив происходит множество операций с памятью для клонирования списка, и при большом объёме данных работа может замедлиться. Если мы выведем данные на график, это будет выглядеть примерно так. Обратите внимание, что есть сезонность, но не очень строгая: некоторые максимумы намного выше, чем другие. Также данные довольно шумные, но общего тренда в них нет. Как и раньше, давайте разобьём наш ряд на обучающую и валидационную выборки. Мы разобьём их по временной отметке 1000. Размер окна зададим 20, размер пакета 32, а размер буфера для перемешивания — 1000. Мы используем тот же самый код windowe_dataset, который использовали всю неделю для преобразования рядов в наборы данных, на которых мы можем проводить обучение.

9(w4)-vide7: Train and tune the model (18.MLg_4c)

We'll go back to the simple DNN that we saw way back in week two for training on and we'll see what happens. We get a chart like this, which at least to the eyeball looks really good, but it has a very large MAE so something must be wrong. Indeed, if we zoom into the results we can see in a little bit more detail about how the forecast behaves in the original data. Our clue to the problem could be our window size. Remember earlier we said it's a 20 so our training window sizes are 20 time slices worth of data. And given that each time slice is a month in real time our window is a little under two years. But if you remember this chart, we can see that the seasonality of sunspots is far greater than two years. It's closer to 11 years. And actually some science tells us that it might even be 22 years with different cycles interleaguing with each other. So what would happen if we retrain with a window size of 132, which is 11 years worth of data as our window size. Now while this chart looks similar, we can see from the MAE that it actually got worse so increasing the window size didn't work. Why do you think that would be? Well, by looking back to the data, we can realize that it is seasonal to about 11 years, but we don't need a full season in our window. Zooming in on the data again, we'll see something like this where it's just the typical time series. Values later on are somewhat related to earlier ones, but that's a lot of noise. So maybe we don't need a huge window of time in order to train. Maybe we should go with something a little bit more like our initial 20, let's try 30. So if we look back at this code, we can change our window size to 30. But then look at the split time, the data set has around 3,500 items of data, but we're splitting it into training and validation. Now 1,000, which means only 1,000 for training and 2,500 for validation. That's a really bad split. There's not enough training data. So let's make it 3,000 and 500 instead. And then when we retrain, we'll get this. Our MAE has improved to 15 but can we make it even better? Well, one thing we can try is to edit the neural network design and height of parameters. If you remember, we had three layers of 10, 10, and 1 neurons. Our input shape is now larger at 30. So maybe try different values here, like 30, 15, and 1, and retrain. So let's switch back to 10, 10, 1 and instead look at the learning rate. Let's tweak it a little. Now after retraining, I can see my MAE has decreased a bit which is good.
---------------------------------------------------------------
Давайте вернёмся к простой глубокой нейросети, с которой мы работали на второй неделе, обучим её и посмотрим, что будет. Мы получим график вроде этого, который на глаз выглядит очень хорошо, но абсолютная ошибка очень высока, а значит, что-то здесь не так. И правда: если увеличить график, мы сможем рассмотреть подробнее, как прогноз ведёт себя по сравнению с исходными данными. Ключом к нашей проблеме может быть размер окна. Помните, раньше мы говорили, что он равен 20, так что в наше тренировочное окно помещается 20 временных отсчётов. И учитывая, что каждый отсчёт равен месяцу в реальном времени, ширина нашего окна получается немногим меньше двух лет. Но если вы вспомните этот график, то по нему видно, что периоды солнечной активности — куда дольше двух лет. Они близки к 11 годам. Некоторые учёные даже говорит, что период может составлять 22 года, где чередуются два различных цикла. Так что же произойдёт, если мы обучим сеть заново с размером окна 132, что соответствует 11 годам? Хотя новый график выглядит похоже, по абсолютной ошибке можно заключить, что стало только хуже, так что увеличение размера окна не сработало. Как думаете, почему? Ну, оглядываясь на данные, мы понимаем, что хотя их периодичность около 11 лет, но нам не надо, чтобы в окно помещался полный цикл. Увеличивая данные опять, мы видим что-то вроде этого, — довольно типично для временного ряда. Более поздние данные как-то зависят от предыдущих, но ещё здесь много шума. Так что возможно, при обучении нам не нужны огромные окна. Возможно, стоит попробовать окно лишь чуть больше, чем наши исходные 20 — давайте попробуем 30. Вернувшись к коду, мы можем заменить window_size на 30. Но давайте ещё посмотрим на split_time: в нашем ряду около 3500 элементов, но мы разделили его на обучающую и валидационную выборки по отметке 1000, что даёт лишь 1000 значений для обучения, и 2500 — для валидации. Это очень плохая разбивка. Нам не хватает данных для обучения. Давайте теперь отделим первые 3500. И когда мы обучим заново, то получим вот что. Наша ошибка улучшилась до 15, но можем ли мы ещё её улучшить? Среди прочего, можно попробовать изменить дизайн нейросети и гиперпараметры. Если вы помните, у нас было три слоя: по 10, 10 и 1 нейрону. Размер входа теперь больше, и составляет 30. Давайте попробуем другие значения, например, 30, 15 и 1, — и обучим заново. К удивлению, мы сделали небольшой шаг назад — абсолютная ошибка выросла. К тому же, дополнительные траты времени на лишние нейроны в слоях — не стоили того. Так что давайте вернёмся к 10, 10, 1, и попробуем поработать с темпом обучения. Немного подстроим его. Теперь, обучив повторно, я вижу, что ошибка чуть-чуть уменьшилась, и это хорошо.

10(w4)-vide8: Prediction (18.MLg_4c)

Out of interest, let's do a prediction. The window size I'm using is 30 steps, and the dataset is 3,235 steps long. So if I want to predict the next value after the end of my dataset, I would use this code. And I would get the result 7.0773993. The dataset goes up to July 2018, so I'm actually predicting 7.077 sunspots for August 2018. And if I look at this chart of observations, which does have some slightly different data from my dataset, I can see that the actual recorded number of sunspots in August 2018 was 8.7. So the prediction isn't too bad, but let's see if we can improve on it. With these settings, I got the MAE down to 13.75, and the prediction was 8.13, which is much closer to the actual real reading of 8.7. There is a random elements in creating models, however, so your results may vary. Doing accuracy based on a single prediction like this is also a recipe for disappointment, and you're much better off evaluating mean accuracy over a number of readings. So here, we looked at using a DNN to predict sunspot values. With a little bit of tuning, we reduced our MAE a bit. And when we tried to predict the next month's value using this model, we got quite close to the actual value. In the next video, you'll go through this workbook to see it in action. And then you should try it out for yourself, to see if you can improve on what I got. After that, you'll look into the RNNs again and see if you can get better predictions using those.
---------------------------------------------------------------
Ради интереса, давайте сделаем прогноз. Я использую размер окна в 30 шагов, а ряд имеет длину 3235 шагов. Так что если я хочу предсказать значение, сразу следующее за моим набором данных, то мне нужно использовать такой код. И он выдаёт прогноз 7.0773993. Набор данных был по июль 2018 г., так что я, по сути, предсказал 7.077 пятен на Солнце в августе 2018. И заглянув в эту таблицу наблюдений, где цифры слегка отличаются от моего набора данных, я вижу, что на самом деле в августе 2018 года отмечалось, в среднем, 8.7 пятен на Солнце. Так что прогноз не так уж и плох. Посмотрим, удастся ли его улучшить. С этими настройками абсолютная ошибка снизилась до 13.75, а предсказание получилось 8.13, что намного ближе к настоящему значению 8.7. Но в создании моделей есть элемент случайности, так что ваши результаты могут отличаться. Также вычисление точности на основе единичного прогноза, как здесь — это путь к разочарованию, так что лучше оценивать среднюю точность для множества показаний. Итак, мы рассмотрели использование глубокой нейросети для прогнозирования количества солнечных пятен. С помощью небольшой подстройки мы слегка уменьшили абсолютную ошибку. А когда мы попытались предсказать значение в следующем месяце, используя эту модель, мы подошли довольно близко к настоящему значению. В следующем видео мы разберём весь этот блокнот, и вы посмотрите его в действии. А затем поработайте с ним самостоятельно, чтобы увидеть, получится ли у вас улучшить мой результат. После этого вы ещё раз вернётесь к РНС и посмотрите, получится ли улучшить предсказания с их помощью.

11(w4)-Sunspots notebooks (Lab 2 & Lab 3): (18.MLg_4c)

The next screencasts will show how you can use different network architectures to predict real world data.
Here is the notebook for DNN only.
C4_W4_Lab_2_Sunspots_DNN.ipynb
Ungraded Lab: Predicting Sunspots with Neural Networks (DNN only)
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W4/ungraded_labs/C4_W4_Lab_2_Sunspots_DNN.ipynb
Here is the version with the combined layers.
C4_W4_Lab_3_Sunspots_CNN_RNN_DNN.ipynb
Ungraded Lab: Predicting Sunspots with Neural Networks
https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/main/C4/W4/ungraded_labs/C4_W4_Lab_3_Sunspots_CNN_RNN_DNN.ipynb
---------------------------------------------------------------

12(w4)-vide9: Sunspots (18.MLg_4c)

In the previous lesson, you looked at using a real world data set, one with readings of sunspot activity over a couple of hundred years. And you saw how to build a simple DNN to predict activity using that data set. Now let's take a look at the notebook and we'll see it in action for ourselves. This code just imports numpy and pyplot and creates a helper function for plotting charts. This code downloads the data set and puts it into the temp directory. It's a very small data set so it should run very quickly. We'll now import the data from the CSV and create numpy arrays from it. We can plot the data to see it seasonality and its noise but there's no noticeable trend. We'll now split the data and setup our constants. Most notably the window size which I've set to 60. This code is a helper function for turning the data into a windowed data set. And now we'll train with a three layer DNN having 20, 10, and 1 neurons. We'll use stochastic gradient descent as our optimizer When the training is done, we can get forecasts across the validation set. And our plot looks pretty good. If we measured the MAE, we're at about 15. You should get slightly different values due to the randomness of the model initialization and stochastic gradient descent. So don't worry if it's a little off. If it is way off, then go back and check your code or restart the runtime and try again.
---------------------------------------------------------------
В предыдущем уроке вы учились работать с набором реальных данных на примере журнала солнечной активности за пару сотен лет. И вы видели, как строить простую DNN для предсказания активности по этим данным. Давайте теперь просмотрим блокнот и увидим его в действии. Как всегда, давайте проверим, установлен ли у вас TensorFlow 2. Да, установлен, так что можно продолжать дальше. Этот код импортирует numpy и pyplot и создаёт вспомогательную функцию для построения графиков. Вот этот код скачивает набор данных и кладёт его во временную папку. Это очень маленький набор данных, так что код должен отработать быстро. Теперь считаем данные из файла и загрузим их в массивы NumPy. Можно вывести данные на график и увидеть в них периодичность и шум, но в них нет заметного тренда. Теперь разделим данные и настроим наши константы. Обратите внимание, что размер окна я установил равным 60. Этот код — вспомогательная функция для преобразования к оконному набору данных. А теперь обучим трёхслойную нейросеть со слоями из 20, 10 и 1 нейрона. В качестве оптимизатора мы используем стохастический градиентный спуск с темпом обучения, равным 1e-7. Когда обучение закончено, мы можем получить прогнозы для валидационной выборки. И наш график выглядит довольно неплохо. Если мы измерим абсолютную ошибку, она будет около 15. Вы можете получить слегка другие данные из-за случайной составляющей при инициализации модели и стохастическом градиентном спуске. Так что не беспокойтесь, если ваше значение немного отличается. Если оно отличается сильно — вернитесь и проверьте ваш код, или перезапустите среду и попробуйте ещё раз.

13(w4)-vide10: Combining our tools for analysis (18.MLg_4c)

So we've looked at the sunspot data using a standard DNN like way back at the beginning of this course. We've also been working a lot with RNNs and a little with convolutional neural networks. So what would happen if we put them all together to see if we can predict the sunspot activity? This is a difficult dataset because like we've seen already, while it's seasonal the period is really long, around 11 years, and it's not perfectly seasonable during that period. So let's take a look at using all the tools we have to see if we can build a decent prediction using machine learning. So here's the first piece of code we can try. I've gone a little crazy here, so let's break it down piece by piece. First of all I'm setting the batch size to 64 and the window size to 60. Then we'll start with a 1D convolution that we'll learn 32 filters. This will output to a couple of LSTMs with 32 cells each before feeding into a DNN similar to what we saw earlier, 30 neurons, then 10, and one. Finally, as our numbers are in the 1-400 range, there is a Lambda layer that multiplies out our X by 400. With the first test run to establish the best learning, rate we get this chart. This suggests the best learning rate for this network will be around 10 to the minus 5. So when I trained for 500 epochs with this setup, here's my results. It's pretty good with a nice low MAE. But when I look at my loss function during training, I can see that there's a lot of noise which tells me that I can certainly optimize it a bit, and as we saw from earlier videos, one of the best things to look at in these circumstances is the batch size. So I'll increase it to 256 and retrain. After 500 epochs, my predictions have improved a little which is a step in the right direction. But look at my training noise. Particularly towards the end of the training is really noisy but it's a very regular looking wave. This suggests that my larger batch size was good, but maybe a little off. It's not catastrophic because as you can see the fluctuations are really small but it would be very nice if we could regularize this loss a bit more, which then brings me to another thing to try. My training data has 3,000 data points in it. So why are things like my window size and batch size powers of two that aren't necessarily evenly divisible into 3,000? What would happen if I were to change my parameters to suit, and not just the window and batch size, how about changing the filters too? So what if I set that to 60, and the LSTMs to 60 instead of 32 or 64? My DNN already look good, so I won't change them. So after training this for 500 epochs, the noise and the loss function actually increased a bit, and that made me want to experiment with the batch size again. So I reduced it to just 100 and I got these results. Now here my MAE has actually gone up a little. The projections are doing much better in the higher peaks than earlier but the overall accuracy has gone down, and the loss has smoothed out except for a couple of large blips. Experimenting with hyperparameters like this is a great way to learn the ins and outs of machine learning, not just with sequences but with anything. I thoroughly recommend spending time on it and seeing if you can improve on this model. In addition, you should accompany that work with looking deeper into how all of these things in machine learning work and Andrew's courses are terrific for that. I strongly recommend them if you haven't done them already.
---------------------------------------------------------------
Итак, мы поработали с историей солнечной активности, применив стандартную многослойную нейросеть, как в самом начале нашего курса. Также мы много работали с РНС, и немного со свёрточными нейросетями. Что же будет, если сложить их все воедино, и посмотреть, сможем ли мы предсказать солнечную активность? Это непростой набор данных, потому что, как мы уже видели, хотя в них есть цикличность, но период очень длинный, около 11 лет, и цикличность проявляется не в полной мере на протяжении этого периода. Так что давайте посмотрим, как использовать все имеющиеся у нас инструменты, и проверим, сможем ли мы получить приличный прогноз при помощи машинного обучения. Итак, вот первый фрагмент кода, который мы попробуем. Я тут немного перемудрил, так что давайте разберём всё по частям. Прежде всего, я установил размер пакета, равный 64, а размер окна — 60. Далее я начал с одномерной свёртки, в которой обучаются 32 фильтра. Выход с неё поступает в пару LSTM, по 32 ячейки в каждой, перед тем, как попасть в нейросеть, подобную той, которую мы видели раньше: 30 нейронов, потом 10, потом 1. И наконец, т.к. наши числа лежат в диапазоне от 1 до 400, здесь добавлен лямбда-слой, умножающий выходное значение на 400. Сделав пробный запуск для определения оптимального темпа обучения, мы получаем такой график. Он подсказывает, что оптимальным темпом обучения для этой сети будет около 1e-5. И после обучения с этими настройками в течение 500 эпох я получил вот такие результаты. Они вполне хороши, абсолютная ошибка невелика. Но при взгляде на функцию потерь в процессе обучения я вижу в её значениях много шума, который говорит о том, что тут можно ещё немного оптимизировать. И как мы видели из предыдущих видео, одним из заслуживающих внимания параметров в подобных обстоятельствах является размер пакета. Так что я увеличу его до 256 и запущу обучение заново. После 500 эпох мои прогнозы немного улучшились, и это шаг в верном направлении. Но посмотрите на шум при обучении. Особенно под конец обучения — функция потерь здесь очень шумная, но это выглядит как периодическая волна. Это говорит о том, что увеличенный размер пакета — это хорошо, но, возможно, чересчур. Это не катастрофа, потому что, как видите, флуктуации очень малы, но было бы очень здорово, если бы нам удалось убрать и эти колебания, что заставляет меня попробовать кое-что ещё. В моей обучающей выборке 3000 элементов. Так почему у меня размер окна и размер пакета являются степенями двойки, которые вовсе не обязательно делят 3000 нацело? Что произойдёт, если я изменю параметры для достижения аккуратной разбивки? И речь не только о размере окна или пакета — как насчёт смены размеров фильтров? Что, если я изменю этот размер на 60? И количество ячеек в LSTM — тоже на 60, вместо 32 или 64? Набор полносвязных слоёв уже выглядит хорошо, так что его я менять не буду. Итак, после обучения этой сети в течение 500 эпох результаты снова улучшились, хотя и всего чуть-чуть. Это показывает, что мы движемся в верном направлении. Интересно, что шум и величина потерь — немного выросли, и это подталкивает меня ещё поэкспериментировать с размером пакетов. Так что я уменьшил его до 100, и получил такие результаты. Тут абсолютная ошибка немного увеличилась. Прогнозы на пиках стали куда лучше, чем раньше, но, в целом, точность упала, а график функции потерь стал более гладким, кроме пары крупных всплесков. Такие эксперименты с гиперпараметрами — отличный способ изучить все тонкости машинного обучения. Не только для временных рядов — а для чего угодно. Я абсолютно рекомендую тратить на это время, проверяя, можете ли вы улучшить модель. Кроме того, во время такой работы стоит глубже изучать, как работают все эти средства машинного обучения. И для этих целей великолепно подходят курсы Эндрю. Я настоятельно их вам рекомендую, если вы их ещё не прошли.

14(w4)- Week 4 Quiz: (18.MLg_4c)

1) How do you add a 1 dimensional convolution to your model for predicting time series data?:
1. Use a Conv1D layer type (+)
2. Use a ConvolutionD1 layer type
3. Use a 1Dconv Layer type
4. Use a 1DConvolution layer type
2) What's the input shape for a univariarte time series to a Conv1D:
1. []
2. [1]
3. [1, None]
4. [None, 1] (+)
3) You used sunspots dataset that was stored in CSV. What's the mane of the Python library used to read CSVs?:
1. PyFiles
2. PyCSV
3. CommaSeparatedValues
4. CSV (+)
4) If your CSV file has a header that you don't want to read into your dataset, what do you execute before iterating through the file using a 'reader' object?:
1. next(reader) (+)
2. reader.read(next)
3. reader.ignore_header()
4. reader.next
5) When you read a row from a reader and want to cast column 2 to another data type, for example, a float, what's the correct sintax?:
1. float(row[2]) (+)
2. Conver.toFloat(row[2])
3. You can't. It needs to be read into a buffer and a new float instantiated from the buffer
4. float f=row[2].read()
6) What was the sunspot seasonality?:
1. 11 years (-)
2. 22 years
3. 4 times a year
4. 11 or 22 year depending on who you ask (+)
7) After studying this course, what neural network type do you think is best for prediction time series like out sunspots dataset?:
1. Convolutions
2. DNN
3. RNN / LSTM ( - )
4. A combination of all other answers (+)
8) Why is MAE a good analytic for measuring accuracy of predictions for time series?:
1. It doesn't heavily punish larger errors like square errors do (+)
2. It punishes larger errors
3. It biases towards small errors
4. It only counts positive errors

15(w4)- Lecture Notes Week 4: (18.MLg_4c)

The lecture notes are available on our community platform. If you're already a member, log in to your account and access the lecture notes here.
NOTE: If you don't have an account yet, kindly follow the instructions here, then come back to this page.
Copyright Notice
hese slides are distributed under the Creative Commons License.
DeepLearning.AI makes these slides available for educational purposes. You may not use or distribute these slides for commercial purposes. You may make copies of these slides and use or distribute them for educational purposes as long as you cite DeepLearning.AI as the source of the slides.
For the rest of the details of the license, see
https://creativecommons.org/licenses/by-sa/2.0/legalcode
---------------------------------------------------------------

16(w4)- Programming Assignment: Adding CNNs to improve forecasts: (18.MLg_4c)

Week 4: Using real world data
https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction/programming/0XyOq/adding-cnns-to-improve-forecasts/lab?path=%2Fnotebooks%2FC4W4_Assignment.ipynb

17(w4)- Wrap up: (18.MLg_4c)

Congratulations on getting this far! In this course, you've dipped your toe into the water of understanding sequences and some of the tools for predicting them! Hopefully, it was a fun journey and we're really looking forward to what you build next! :)
---------------------------------------------------------------
Поздравляем! В этом курсе вы погрузились в воду понимания последовательностей и некоторых инструментов для их предсказания! Надеюсь, это было веселое путешествие, и мы с нетерпением ждем того, что вы создадите дальше! :)

18(w4)-vide11: Congratulations! (18.MLg_4c)

So that brings you to the end of this course on sequences and prediction. I hope you've enjoyed looking at the myriad of different ways that you can use machine learning to make predictions based on sequential and time series data. That being said, you've really only scratched the surface of what's possible, and you've only just taken the first steps on your journey. There's lots more to learn, but with what you've achieved over the last few weeks, you're well-equipped to dive deeper and look at more complex scenarios, including things like multivariate time series data. We really hope you've enjoyed this course, and as always we'd love to hear your feedback as we create more. Thank you.
---------------------------------------------------------------
Итак, мы подошли к концу этого курса, посвящённого временным рядам и их прогнозированию. Надеюсь, вам понравилось изучать бесчисленное множество разных способов, которыми можно использовать машинное обучение для прогнозирования последовательностей и временных рядов. Вы, так сказать, лишь немного поскребли по поверхности возможного, и сделали лишь первые шаги в своём путешествии. Вам предстоит изучить ещё массу всего, но с тем, чего вы добились за истекшие несколько недель, вы уже подготовлены к более глубокому погружению, к работе с более сложными случаями, включая, например, многовариантные временные ряды. Очень надеюсь, что вы получили от курса удовольствие, и мы, как всегда, будем рады получить от вас отзывы, чтобы творить и дальше. Спасибо.

19(w4)-References: (18.MLg_4c)

This is a compilation of resources appearing in the lecture videos, ungraded labs, and assignments.
Week 1:
● Moore's Law (Wikipedia)
https://en.wikipedia.org/wiki/Moore%27s_law
● Spurious Correlations: Arcades vs Doctorates (Tyler Vigen)
https://tylervigen.com/view_correlation?id=97
● Birth and Death Rate in Japan (Wikipedia)
https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Bdrates_of_Japan_since_1950.svg/450px-Bdrates_of_Japan_since_1950.svg.png
● Global Temperature and Carbon Dioxide (GlobalChange.gov)
https://www.globalchange.gov/browse/multimedia/global-temperature-and-carbon-dioxide
● Slope-Intercept Form (Wikipedia)
https://en.wikipedia.org/wiki/Linear_equation#Slope–intercept_form_or_Gradient-intercept_form
● Tensorflow API (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf
● Numpy (Official Website)
https://numpy.org
● Pyplotv (Official Website)
https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.html
● Keras Metrics (Official Website)
https://www.tensorflow.org/api_docs/python/tf/keras/metrics/
---------------------------------------------------------------
Week 2:
● tf.data API (TF Documentation)
https://www.tensorflow.org/guide/data
● tf.data.Dataset (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/data/Dataset
● Flatten a dataset of windows (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/data/Dataset#flatten_a_dataset_of_windows_2
● LearningRateScheduler (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/LearningRateScheduler
---------------------------------------------------------------
Week 3:
● Huber Loss (Wikipedia)
https://en.wikipedia.org/wiki/Huber_loss
● SimpleRNN (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/layers/SimpleRNN
● Lambda Layer (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda
● Activation Functions (Wikipedia)
https://en.wikipedia.org/wiki/Activation_function#Table_of_activation_functions
● LSTM (DeepLearning.AI)
https://www.coursera.org/lecture/nlp-sequence-models/long-short-term-memory-lstm-KXoay
● LSTM Layer (TF Documentation)
https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM
---------------------------------------------------------------
Week 4:
● Convolutional Neural Networks (DeepLearning.AI)
https://www.coursera.org/learn/convolutional-neural-networks
● Mini-batch Gradient Descent (DeepLearning.AI)
https://www.youtube.com/watch?v=4qJaSmvhxi8
● Sunspots Dataset (Robert Valt)
https://www.kaggle.com/datasets/robervalt/sunspots
● Solar Conditions (Australian Bureau of Meteorology)
https://sws.bom.gov.au/Solar/1/6
● Daily Minimum Temperatures in Melbourne (hosted by Jason Brownlee, source: Australian Bureau of Meteorology)
https://github.com/jbrownlee/Datasets/blob/master/daily-min-temperatures.csv

20(w4)-Acknowledgments: (18.MLg_4c)

In addition to the original Curriculum Developers, the following people made significant contributions to the Course 4 refresh:
Quiz Revisions:
Diego Peluffo
Engineering Support:
Andres Zarta
Testing and Mentorship:
Giovanni Lignarolo
Deepthi Locanindi
Chris Favila
Testers:
Xinyue Zhao
Álvaro Ramajo Ballester
Mayank Ghogale
Pawel Piela
Bartosz Pieniak
Nilosree Sengupta
Steve Sun
Davide Tisi
Marketing:
Ishita Chaudary
Video Production:
Diego Peluffo
Additional Administrative and Content Support:
Ryan Keenan
Inhae Koo
Lara Pheatt-Pitzer
Muhammad Mubashar
Christopher Moroney
Emma Afflerbach
Nikki Gibson
Finally, our sincerest thanks to YOU, for enrolling in this Specialization and becoming part of our global community of learners!

21(w4)-vide12: Specialization wrap up - A conversation with Andrew Ng (18.MLg_4c)

Congratulations on coming to the end of this TensorFlow and practice specialization. In the four courses, you learn how to build a deep neural network, how to build a conv net, how to build sequence models for NLP and finally, how to build time series models. You've built and you've learned a lot of stuff in the specialization, and I hope you give yourself a pat on the back for getting to the end. We've really come a long way, if you remember our very first lesson is we did two sets of numbers where the relationship was y equals 2x minus 1. We had a little DNN that people use then to learn that and to do that pattern matching of the x against y, but since then, we've gone into computer vision, natural language processing, time sequence modeling, sunspots, all that thing. So I really think that you've really just taken the first step though on a much bigger journey, there's so much more stuff to learn. One of the pieces of feedback that we get from students is that they really love this, but they want to learn more. I always recommend that the other specializations that Andrew has done that I've personally learned from as well. So if you really want to go into more depth into for example, how an LSTM works or how an RNN works, or how even a convolution works, there's some great material out there, and we've designed these materials to mesh with each other. So if you really want to learn in-depth, Andrew is the master, and if you want to learn how to then apply that to code and how to take that, and put it into practice, then this course and future courses that we're working on will be really all around that. So we hope to see you there. As Lawrence said, I hope this is just a part of your journey to become great at deep-learning. The deep learning specialization compliments this one, and so if you want to go into greater depth, you can check that out too. There's still more to learn. So Lawrence and I are still going to be continuing to build additional specializations to help you learn even more about TensorFlow. Looking forward to it. Working with Lawrence has been the highlight of these past few months and I look forward to building more courses together. To all of you that stuck with us throughout all this period, thank you for all the hard work you put into learning these things and keep watching the space, we'll have more things for you in the future. Thank you.
---------------------------------------------------------------
Поздравляю с окончанием специализации "TensorFlow на практике". В четырёх курсах вы научились строить глубокие нейросети, строить свёрточные сети, модели последовательностей для естественных языков, и, наконец, строить модели для временных рядов. Вы многое построили и многому научились на нашей специализации, и я надеюсь, вы одобрительно похлопали себя по спине за то, что дошли до конца. Мы действительно прошли долгий путь. Если помните, на первом уроке мы взяли два набора чисел, отношение между которыми было y=2x-1. У нас была небольшая полносвязная нейросеть, которую использовали для обучения и следования этому шаблону соответствия между x и y. Но с тех пор мы познакомились с компьютерным зрением, обработкой естественных языков, моделированием временных рядов, солнечной активностью, и т.п. И я считаю, что вы и правда сделали лишь первый шаг на очень большом пути: ещё столь многому вам предстоит научиться. И из отзывов студентов мы видим, что им всё это очень понравилось, но они хотят научиться большему. Я всегда рекомендую другие специализации, которые подготовил Эндрю, я и сам учился на них. Так что если вы действительно хотите углубиться в то, как, к примеру, работает LSTM, или как работают РНС, или даже как работает свёртка, — там есть великолепные материалы, и мы спроектировали эти материалы так, чтобы они перекликались друг с другом. Так что если вы и правда хотите более глубоких знаний, то Эндрю — ваш наставник, а если затем захотите научиться применять всё это в коде, как применять эти вещи на практике, — тогда данный курс — а также будущие курсы, над которыми мы работаем, — будут ждать вас. Так что мы надеемся вас там увидеть. Как уже сказал Лоуренс, я надеюсь, что это лишь часть вашего путешествия к тому, чтобы стать мастером в глубоком обучении. Специализация по глубокому обучению дополняет эту, и если вы хотите погрузиться в детали, то можете рассмотреть её в качестве варианта. Ещё столько всего предстоит изучить. Так что Лоуренс и я продолжаем готовить новые специализации, чтобы помочь вам узнать о TensorFlow ещё больше. С нетерпением жду этого. Работа с Лоренсом была лучшей частью последних месяцев, и мне не терпится поработать над новыми совместными курсами. А всех вас, кто оставался с нами на протяжении этого периода, я благодарю за все усилия, вложенные вами в изучение этих тем. Оставайтесь на связи, у нас ещё будут для вас новинки. Спасибо.

22(w4)-What next?: (18.MLg_4c)

Ready to deploy your models to the world? Learn how to go live with your models with the
TensorFlow: Data and Deployment Specialization.
https://www.coursera.org/specializations/tensorflow-data-and-deployment?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=TF1CourseItem
Looking to customize and build powerful real-world models for complex scenarios? Check out the
TensorFlow: Advanced Techniques Specialization.
https://www.coursera.org/specializations/tensorflow-advanced-techniques?utm_source=deeplearning-ai&utm_medium=institutions&utm_campaign=TF1CourseItem

23(w4)-(Optional) Opportunity to Mentor Other Learners: (18.MLg_4c)

Our sincere thanks to you for enrolling in this specialization and becoming part of our global community of learners!
If you are passionate about volunteering and giving back to the community by guiding other learners to complete this specialization and/or testing other specializations published by Deeplearning.AI in Coursera, then sign up for the DeepLearning.AI Mentorship Program.
https://docs.google.com/forms/d/e/1FAIpQLScHp04An_g9UJq5fX_uOVGGAUh1mZttbE6hDePqR58SrWDIyQ/viewform
Someone from the DeepLearning.AI staff will reach out to you when positions suitable to your profile are available.
Note: It is not mandatory to sign up. It is a purely optional and voluntary service


mpublic


My publications (mpublic)

1. Методика прогнозування технічного стану вузлів ГТД в умовах експлуатації. :
Стаття (8)
Збірник наукових праць. – К.: Науковий центр повітряних сил збройних сил України, 2004. - №7. – с. 251–258.
Чоха Ю.М., Галицький С.П.
2. Дослідження впливу профілю лопаті несучого гвинта на аеродинамічні характеристики ротора автожиру. :
Тези доповіді (1)
ПОЛІТ-2005: V міжнародна науково-практична конференція молодих учених і студентів, 12-13 квітня 2005 р.: тези доп. – К. 2005.- С. 8.
Іщенко С.О., Галицький С.П.
3. Дослідження стійкості автожиру різних аеродинамічних компонованих систем. :
Тези доповіді (1)
ПОЛІТ-2005: V міжнародна науково-практична конференція молодих учених і студентів, 12-13 квітня 2005 р.: тези доп. – К. 2005.- С. 9.
Іщенко С.О., Галицький С.П.
4. Оптимізація геометричних характеристик профілю лопаті несучого гвинта автожиру.: (1, ukr) ::
Стаття (5)
Вісник Національного авіаційного університету. - 2005. - №4. – С. 55 – 49.
Іщенко С.О., Галицький С.П.
(Optimization of geometrical characteristics of a structure of the profile of the carrying airscrew of autogyro.)
The data research are devoted questions of geometry profile influence on aerodynamic characteristics of the carrying airscrew rotor of autogyro. The linear regression analysis is used for reception of a new profile structure which has essentially improved aerodynamic performances of the carrying airscrew of autogyro.
https://jrnl.nau.edu.ua/index.php/visnik/article/view/1247
DOI: https://doi.org/10.18372/2306-1472.26.1247
5. Дослідження динаміки роботи ротора автожиру. :
Тези доповіді (1)
ПОЛІТ-2006: VІ міжнародна науково-практична конференція молодих учених і студентів, 11-12 квітня 2006 р.: тези доп. – К. 2006.- С. 12.
Іщенко С.О.
6. Модель несучого гвинта, що знаходиться в стані авторотації, безпілотного літального апарату типу «автожир». :
Тези доповіді (1)
Актуальні проблеми розвитку авіаційної техніки
науково практична конференція, 19-20 червня 2008 р.: тези доп. – К. 2009. - С.31.
Іщенко С.О.
7. Модифікація аеродинамічних профілів для зменшення впливу нестаціонарності.: (2, ukr) ::
Стаття (5)
Вісник Національного авіаційного університету. - 2008. - №3. – С. 39 – 43.
Переверзєв А.М., Пашинський Т.Е.
(Modification of the aerodynamic profile to reduce the impact of non-stationary.)
The review of works on an unstationary flow on wing profiles which forms change of vortex structure flow and essentially changes its aerodynamic characteristics is considered. Updating of contours of a profile can be, criterion of reduction of an unstationary flow influence, and also lead to reduction of an unstationary flow influence on aerodynamic characteristics.
https://jrnl.nau.edu.ua/index.php/visnik/article/view/1587
DOI: https://doi.org/10.18372/2306-1472.36.1587

8. Экспериментальные исследования состояния пограничного слоя, возмущенного генератором вихрей.: (3, ukr) ::
Стаття (6)
Системи озброєння і військова техніка. - 2008. - №3. – С. 104 – 109.
Іщенко С.О., Аббас Фадиль Махмуд
(Experimental researches of the state of border-line layer, indignant at generator of whirlwinds
S.A. Ischenko, O.V. Bondar', Abbas Fadil' Makhmud)
The results of experimental researches of the state of boundary layer indignant at the diffuzornim generator of whirlwinds are resulted. Researches are conducted in the wind-channel of the UTAD-2-2 National aviation university, having a certificate on metrologicheskie descriptions of stream and mean of measuring, at the location of generator of whirlwinds on a flat plate. It is proved, that the law of distributing of pulsations of speed in a boundary layer differs from normal. It is shown, that the generator of whirlwinds changes the epyuru distributing of speed on the height of boundary layer.
https://www.hups.mil.gov.ua/periodic-app/article/1287/eng
9. П'ятикомпонентна тензометрична система вагових випробувань для аеродинамічної труби ТАД-2 НАУ. :
Тези доповіді (1)
ПОЛІТ-2009: ІХ міжнародна науково-практична конференція молодих учених і студентів, 8-10 квітня 2009 р.: тези доп. – К. 2009.- С. 5.
Смаковий Я.О.
10. Багатокомпонентна система вимірювання аеродинамічних навантажень.: (4, ukr) ::
Стаття (9)
Вісник Національного авіаційного університету. - 2009. - №2. – С. 8 – 16.
Іщенко С.О.
(Multi-system measurement of aerodynamic loads)
The basic features of projection and manufacture of multicomponent system of measurement of aerodynamic loads of beam type are observed. The previous estimation of metrology performances of the gained system is conducted.
https://jrnl.nau.edu.ua/index.php/visnik/article/view/1701
DOI: https://doi.org/10.18372/2306-1472.39.1701
11. Експериментальне обладнання для дослідження авторотуючого несучого гвинта. :
Тези доповіді (1)
ПОЛІТ-2010: Х міжнародна науково-практична конференція молодих учених і студентів, 7-9 квітня 2010 р.: тези доп. – К. 2010. – Т.І.- С. 317.
12. Пристрій для визначення поля індуктивних швидкостей несучого гвинта в аеродинамічній трубі.: (5, ukr) ::
Патент (3)
Пат. 52913 Україна, МПК G01M 9/00/ - №201004421; Заявл. 16.04.2010; Опубл. 10.09.2010, Бюл. №17. – 3 с.
Давидов О.Р.,Іщенко С.О.
(Attachment for the designation of the field of inductive slips of a bearing screw in a wind tunnel.)
An attachment for designating the field of inductive fasteners of a bearing screw in an aerodynamic tube, which can hold a bearing screw in itself, a holder with a winding nozzle, two linear hydraulic drives, a mechanism for linking with supports, a block of twisting, setting h of forced movement, moreover, the first linear hydraulic drive ensures vertical movement holders, and the other linear hydraulic drive, through the linkage mechanism, secures the wraparound movement of the holder in the area where the hydraulic drives are located, which is inspected by the fact that two sensors of the apex position are additionally introduced, the third linear hydraulic drive, which from one side, so the very same as the first hydraulic drive by the mechanism of connection, and the other side of the connection with the body of the aerodynamic tube, moreover, the control of all three by hydraulic actuators is behind the auxiliary control block, which is the first one and the other input of the connection with the outputs of the sensors in the apex position nya hydraulic drive, as well as between the linkage mechanism and the aerodynamic tube housing.
https://uapatents.com/3-52913-pristrijj-dlya-viznachennya-polya-induktivnikh-shvidkostejj-nesuchogo-gvinta-v-aerodinamichnijj-trubi.html
13. Комплексний підхід до оцінки нерівномірного розподілу поля індуктивних швидкостей по диску авторотуючого несучого гвинта. :
Тези доповіді (4)
АВІА-2011: X міжнародна науково-технічна конференція, 19-21 квітня 2011 р.– К. 2011. – Т.II. – С. 17.32-17.35.
14. Evaluation of the stability derivatives in a longitudinal, lateral and transverse motion of the unmanned aerial vehicle in the curvilinear flight with rotation. :
Тези доповіді (3)
“Авіація у XXI столітті” – “Безпека в авіації та космічні технології”: V Всесвітній конгр 25-27 вересня 2012 р. – К.2012. – Т.І. С. 1.3.38-1.3.40.
Плахотнюк Є.С.

15. Дослідження аеродинамічних характеристик профілю в аеродинамічній трубі Утад-2 НАУ при кутах атаки 0-360 град. :
Тези доповіді (4)
АВІА-2013: XІ міжнародна науково-технічна конференція, 21-23 травня 2013 р.– К. 2013. – Т.II. – С. 17.32-17.35.
16. Parametric analysis of longitudinal stability unmanned aerial vehicle.: (6, eng) ::
Стаття (7)
Proceedings of the National Aviation University. - 2013. - №3. – p. 22 – 28.
Ударцев Є.П., Плахотнюк Є.С.
(Udartsev, I., Bondar, A., & Plakhotniuk, I.)
We consider the aerodynamic characteristics of unmanned aircraft container type, which were obtained in a wind tunnel and refined amended by soot blowing elements propeller system and the influence of the earth's surface. The estimation of longitudinal static stability and its dependence on altitude, damping, coordinates of center of gravity, shoulder horizontal tail, wings rejection of mechanization. The variation of these parameters enables to optimize balancing system with minimal losses.
DOI: https://doi.org/10.18372/2306-1472.56.5411
http://jrnl.nau.edu.ua/index.php/visnik/article/view/5411
17. The experimental equipment for wind tunnel TAD - 2 NAU :
Тези доповіді (4)
“Авіація у XXI столітті” – “Безпека в авіації та космічні технології”: V Всесвітній конгр. 25-27 вересня 2014 р. – К.2014. – Т.І. С. 1.2.1-1.2.4.
Іщенко С.О.
18. Navigation range and duration of flight of unmanned aerial vehicle: (7, eng) ::
Стаття (10)
Proceedings of the National Aviation University. - 2014. - №3. – p. 33 – 42.
Ударцев Є.П., Плахотнюк Є.С.
(Udartsev, I., Bondar, A., & Plakhotniuk, I. )
The problem of calculation of navigation range and the flight duration, different from estimated technicalrange by the accounting of operational features in balancing, influence of atmospheric flight conditions and the specificfeatures influencing aerodynamic resistance of unmanned aerial vehicle is considered.
DOI: https://doi.org/10.18372/2306-1472.60.7562
https://jrnl.nau.edu.ua/index.php/visnik/article/view/7562

19. Пристрій для визначення поля індуктивних швидкостей несучого гвинта в аеродинамічній трубі: (8, ukr) ::
Патент (4)
Пат. 94188 Україна, МПК G01M 9/00/ - №2013 12116; Заявл. 16.10.2013; Опубл. 10.11.2014, Бюл. №21. – 7 с.
Давидов О.Р., Іщенко С.О.
(Attachment for the designation of the field of inductive slips of a bearing screw in a wind tunnel)
An attachment for designating the field of inductive fasteners of a load-bearing screw in an aerodynamic tube, which can be used to extend the load-bearing screw, a holder with a winding nozzle, three linear hydraulic drives, a mechanism for linking with supports, a block for turning by a drive, a task in impulsive movement, two sensors of the top position, and the first line hydraulic drive secures the vertical movement of the holder, another linear hydraulic drive through the linkage mechanism secures the wraparound movement of the holder in the area where the hydraulic drives are located, and the third linear hydraulic drive, which connects one on the other side, just like the first hydraulic drive with a linkage mechanism, and on the other side of the connection with the body of the aerodynamic tube, moreover, the control of all three by hydraulic drives is behind the auxiliary block of the control, which is connected by the first and the other input to the outputs of the sensors of the apex position, which are rotated between the mechanism linkage and first hydraulic drive, as well as between the mechanism of sound 'viscosity and the body of the aerodynamic tube, and the third input of the system with the command of the controlled displacement, which is controlled by the addition of the third sensor of the apex position, the electric drive of the wraparound ruhu, which at one end of the connection holder, and the other through the sensor of the apex position with vimiryuvalny nozzle, the output of which is connected to the fourth input of the keruvannya block by the drive, and one of the outputs of the kerubanny block by the drive is connected to the inlet of the keruvannya to the electric drive of the wrapping ruh.
https://uapatents.com/8-94188-pristrijj-dlya-viznachennya-polya-induktivnikh-shvidkostejj-nesuchogo-gvinta-v-aerodinamichnijj-trubi.html
20. Лопать несучого гвинта: (9, ukr) ::
Патент (4)
Пат. 98644 Україна, МПК B64C 27/72/ - №2014 04085; Заявл. 16.04.2014; Опубл. 12.05.2015, Бюл. №9. – 4 с.
Ударцев Є.П. Давидов О.Р.
(Propeller blade)
1. The blade of the main screw, which contains the crown part, the central part, the tip, while the inflow is made in the central part of the blade, which is distinguished by the fact that the inflow is sequentially arranged in a row on the front and rear edges of the blade.
2. The propeller blade according to item 1, which is characterized by the fact that the forming surfaces of the inflow have the same geometric profile parameters as those used for the central part of the blade.
https://uapatents.com/5-98644-lopat-nesuchogo-gvinta.html
21. Дослідження характеристик малогабаритного шестиствольного приймача повітряного тиску :
Тези доповіді (5)
АВІА-2017: XІІІ міжнародна науково-технічна конференція, 19-21 квітня 2017 р.– К. 2017. – С. 22.40-17.44.
Дегтярьов В.В.


G_Events


Video. (G_Events)

1.Introduction ML Bootcamp (06.07):
(https://www.youtube.com/watch?v=WvQtDs7WJII&t=2s)
1) Причини вивчати МЛ: персоналізоване навчання, розробка лікарських засобів, аналіз ринку і прогнозування, виявлення загроз кібербезпеки, чат боти, автоманизація.
2) Кар'єрний розвиток з ML - навичками: ML, Data Engineers, Automation Engineers, NLP Engineers, AI Experts, Research Scientist, Pre-sales ML Solution Engineer.
3) Можливості під час курсу ML Bootcamp: course for two months (backpack)
4) TensorFlow Certificate on Coursera: + google certification, vaucher from 15 september to 31 december.
5) Kaggle: start 21 August (first 50 peoples take mini backpack).
6) Як пройти ML Bootcamp з користю: work with webinar.
7) TensorFlow Developer Certification: need PyCharm.
8) Q & A: popular chatBot (may be first for ML)

2.Career consultation with Google (11.07):
(https://www.youtube.com/watch?v=1kMr_16zUqQ)
1) Про специфіку роботи в різних типах компаній: Startup "learning by doing", Corporate, Outsource/Outstaff - corporate, NGO - non-rank organizations.
2) Як покращити своє резюме та презентаці для потенційних роботодавців: структура рузюме (Contacts: email, phone, Linkedin, Github; Summary/ Skills; Work Experience; Honours / Awards, Education (on years)), Контент (кастомізація під вакансію(вимоги з вакансіЇ); стратегічний підхід до контенту, перерахуйте технічні та функціональні обовязки, досягнення та вплив), Формат (1 А4.pdf, поточний досвід, список досягнень, візуальний баланс), Присутність Linkedin, Github (https://www.canva.com, google doc)
3) Як проходять співбесіди в різних компаніях, включаючи технічні та поведінкові інтервю: рекрут, технічне інтервю, дом завдання, зустріч з командою, поведінкове інтервю.
4) Як вести перемовини щодо винагороди та інші важливі деталі: дослідження ринку, розуміння структури компенсації, перегляд зарплати, бенефіти та страховка, можливості росту, Counter offer завжди мотивує компаню запропонувати більше
5) Q & A: Linkedin, dou, djinni (aihouse.org.ua)

3.Q&A session_1 (13.07):
(https://www.youtube.com/watch?v=TKKIqLKtqUM)
1) Щоб досягнути максимуму: -зрозуміти логіку кожного кроку(щоб було все зрозуміло, чому так а не інак, + ChatCPT);
- закінчили лабораторну, відкриваємо чистий ноутбук і кодимо самостійно;
- перерви обов'яково
- систематизувати навчання (завдання на кожний день)
- Google Bard AI (чат бот АІ), періодично повторювати пройдений матеріал, моделі
2) малими частинами, але часто; читати англійською;

4.MLOps Best Practices, how to build a scalable & reliable ML System (18.07):
(https://www.youtube.com/watch?v=UmQQY09hyc0)
Jakob Porschmann
- One Decade of Learnings from scaling ML o BNs of Users
- Only a tiny percentage of ML models make it to prod..
But why?
- Companies aim to do advanced ML but are missing solid foundations: Skills & Tools; Meaningful Applications; Data Relevance % Quality
- ML algorithms are NOT the competitive advantage, but high quality data & solid ML pipelines.
- Let's discuss how to: 1)collect the right data in the right quality; 2)tackle ML engineering complexity; 3)design an ML platform for business value.:
1) Assuring data quality, always
Design your ingestion pipeline flexibly and growth oriented, Consider: ETL vs ELT (where to process); stateful vs. stateless processing (how to process); ingestion volume. frequency and elasticity (how much to process); flexibility in data schemes (what to process); modularity of producers and consumers (of/for whom to process)
Google Cloud Platform:
Reliable, scalable and automated ML training & serving
Design your training pipeline rapid experimentation & business impact: You will want to retrain your models; You will need to retrain your models; Complexity comes from ML Engineering, not so much modelling.
Design your serving architecture for scalability and availability: volume of incoming inference requests (how much to serve); inference latency meeds (how quickly to serve); model residency (where to serve); feature serving pipeline (what to serve)
- Measure for business value
Business impact is ultimately the only reason any ML model exists: Define your specific & measurable northstar; Measure model impact; Translate Northstar to ML product ROI
- So where start? Build a data-driven culture; Make coherent tooling choices; Assure top quality data; Experiment rapidly & measure relevance.
- Cloud AutoML: — набор продуктов для машинного обучения, которые позволяет разработчикам с ограниченным опытом работы в области машинного обучения использовать технологии обучения и создания нейронных сетей.

5.Potential of building with Large Language Models (25.07):
(https://www.youtube.com/watch?v=PkN9ROGd_FY)
Vaibhav Singh:
Language Model.
Why Large language Models (LLMs)?
Transformers.
How to make LLVs work?
Prompting in action.
Building with LLMs.
Q & A session.
A language model is a statistical method that predicts the next word in a sequence of words.
Prompting can help a large language model to perform usefully on seen and unseen tasks

6.Deep Learning: Fully Connected Neural Networks (01.08):
(https://www.youtube.com/watch?v=ENi5SaTbVVQ)
Varen Kohli
Artificial Intelligence: Feature Engineering; Training; Test and Validation (Lifecycle of AI model)
https://quickdraw.withgoogle.com
Linear & Non Linear Data
ReLU, SoftMax
Reducing Loss: we can take small steps in the negative gradient direction that minimizes loss; this optimization strategy is called Gradient Descent
Live use cases
TensorFlow - Neural Network Playground (site for play from course)

7.Q&A session_2 (03.08):
(https://www.youtube.com/watch?v=ulzjjd5laN0&t=1s)
Need reading new articles, every day

8.What Can You Build with Embeddings (15.08):
(https://www.youtube.com/watch?v=OWnyDBfriRw)
Ivan Cheung, Engineer Google
What are embeddings
Demo: Embeddings for retrieval
Embedding application architecture
Out of scope
How to train embeddings
Mathematics of embeddings
Q & A session
---------------------
Embeddings let us encode words, documents, images, etc. into numerical vectors
Embeddings are created be passing the word or document through an embedding model
Embeddings are a low-dimensionality representation of higher-dimensionality data that retains semantic information
Vertex AI Embeddings API + Matching Engine
https://ai-demos.dev/demos/matching-engine

"9.Q&A session_3 (17.08):
(https://www.youtube.com/watch?v=QBEV6kK4uEo)
Bohdan Knysh,
БПЛА + Neural network, автономні системи наведення
Поради:
math free brow math loud ??? (for Data Science)
ML (Andrej Karpathy) https://www.youtube.com/@AndrejKarpathy/featured
----------------------
https://www.youtube.com/@TwoMinutePapers/featured
TensorFlow or PyTorch
""Computer Vision: Algorithms and Applications"" от Richard Szelisk (2012)
+ Wikipedia, last publication book
CV must be sent to the company (every day)"

10. Kaggle-змагання: питання та правила (22.08):
(https://www.youtube.com/watch?v=C8y1-nxQpzI)
1) Що таке Kaggle - платформа для змагань DS, ML.(брати участь у змаганнях, знаходити та публікувати dataset, досліджувати та будувати моделі, працювати з іншими data scientista, ML інженерами, навчатися
2) Які переваги участі у змаганнях Kaggle - нові практичні навички, доповнення портфоліо, робота із визначеними дедлайнами, робота в команді, зворотній зв'язок від експертів, нетворкінг з іншими фахівцями, вигравати призи
3) Особистий досвід - швидкий перехід з розробки в сферу DS, виділяє резюме серед інших, дає досвід роботи з різними даними, тримає в курсі останніх трендів та сучасних підходів
4) Оцінка змагання - основна метрика: наскільки дообре модель може передбачити таргетовану змінну - точність, швидкість, легкість інтерпретації
5) Як відбуваються змагання Kagle -
6) Як взяти участь у змаганні у рамказ ML Bootcamp - 21.08 - 04.09, eng, log in Kaggle
7) Поради для успішної участі - правильно підбирайте змагання, спочатку гарно зрозумійте правила та метрики, уважно дослідіть дані, почніть з простого, продумайте коректній процес валідації, не бійтеся експериментувати, читайте та беріть участь в дискусіях, досліджуйте поередні рішуння та статті по темі, не здавайтесь занадто швидео
Сесія запитань та відповідей -

11. Q&A session_4 (24.08):
(https://www.youtube.com/watch?v=CRM5qf70O1k)
Galuh Sahid taking about Kaggle model, dataset and etc

12. Q&A session_5 (31.08):
(https://www.youtube.com/watch?v=vX--bw21Vzs)
Ігок Бірук
Чому датасет такий не якісний? Чи відкриють код в кого +0,95?
1. deeplearning.ai (Andrew Ng ML, DL)
2. fast.ai (practical deep learning for beginners)
3. http://cs231n.stanford.edu (Deep Learning for Computer Vision)
4. https://www.deeplearningbook.org (Deep Learning)
5. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow
6. Approaching (Almost) Any Machine Learning Problem, Abhishek Thakur
----------------------
13. How to prepare for certification TensorFlow (05.09):
(-)
----------------------
All events:
(https://rsvp.withgoogle.com/events/ml-bootcamp-ukraine/home)
----------------------
TensorFlow Developer Certificate:
(https://www.tensorflow.org/certificate)
( https://app.trueability.com/signin )


F1


Links: (F1)

https://www.youtube.com/@Deeplearningai/playlists
---------------------------------------------------------------
https://developers.google.com/machine-learning/foundational-courses
---------------------------------------------------------------
https://www.youtube.com/playlist?list=PLOU2XLYxmsILr3HQpqjLAUkIPa5EaZiui
---------------------------------------------------------------
https://rsvp.withgoogle.com/events/ml-bootcamp-ukraine/additionalcourses_f2b8cd
“COURSERA_CAREERS”: https://www.coursera.org/articles/job-search-guide-resources?utm_source=marketing&utm_medium=email&utm_campaign=37786&sfmc_id=176023098&sfmc_key=0038W00002CxLqxQAF
---------------------------------------------------------------
Big Interview: https://coursera.biginterview.com/register?utm_source=marketing
---------------------------------------------------------------
resumeworded: https://resumeworded.com/coursera?utm_source=marketing&utm_medium=email&utm_campaign=37786&sfmc_id=176023098&sfmc_key=0038W00002CxLqxQAF
password: COURSERA_2021
---------------------------------------------------------------
online translate, resume, virtual W11, linkedin, github
---------------------------------------------------------------
.- simple code model every week; all model for ML; download all datasets; publications; video events; add courses from rsvp.withgoogle.com…
---------------------------------------------------------------
https://docs.google.com/forms/d/e/1FAIpQLSdt9nMUQNqDrtcxqNm3ZCOtAGCrt6VxuF6sfQvCneg90AE1Mg/viewform
---------------------------------------------------------------
Best GPT AI
https://internetua.com/top-10-neiromerej-dlya-sprosxennya-vashoyi-roboti
...

>>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1 <<<<<<< HEAD ======= >>>>>>> d6f7984e73fa0d2e71da759b536b3b74bc1c28c1